Declare function with property in one statement? [duplicate] - javascript

This question already has answers here:
Is it possible to initialize an object as a function with properties?
(2 answers)
Closed 1 year ago.
I know that I can create a function:
const fn = () => {}
And I know that I can attach a property to it:
fn.a = 'a'
Can I use some kind of object literal syntax to do what I did above in one statement?
I'm thinking something along the lines of:
const fn = {
(): {},
a: 'a'
}

You could do it in one statement like this.
const fn = Object.assign(() => {}, { a: 'a' });

How about we make a little utility function to accomplish that?
function createFunc(func, props) {
Object.keys(props).forEach((key) => (func[key] = props[key]));
return func;
}
const f = createFunc(() => console.log("hello"), { a: "A", b: "B" });
f();
console.log(f.a);
console.log(f.b);

Related

what is the meaning of ({ a } = b); in javascript? [duplicate]

This question already has answers here:
Object destructuring without var, let or const
(4 answers)
Closed 1 year ago.
let b = { a: 123123123 };
try {
({ a } = b); <<< what is the meaning of ()
} catch (error) {}
console.log({'a':a})
why this script work, what is the meaning of () in try-catch .
the { a } = b is wrong but ({ a } = b) is correct and the variable will go out of try-catch and give new value to a.
if there are a function in () may be a IIFE, if in expressions the () is a Grouping operator.and in my example,what is the meaning of ()
A pair of parenthesis force the contents to be treated as an expression instead of a statement.
This causes the { to be seen at the start of an object or dereferencing structure (the latter in this case) instead of a block.

How can I declare a variable as a function as well as assign values to it [duplicate]

This question already has answers here:
Adding custom properties to a function
(10 answers)
javascript adding property to function
(2 answers)
Properties of Javascript function objects
(5 answers)
Closed 1 year ago.
I tried this:
var fun = function(){ console.log("booyah"} , {
hell: function(){
console.log("hello");
},
boy: ()=>{
alert("blah");
}
};
fun.boy();
I want that first I call fun function and then Access functions I have stored as objects. But I am getting errors . How can I fix it? Or is there any other way to do that?
Please help.
You can achieve this kind of result by editing the prototype of the function.
Example:
function foo() {
const something = 'the thing';
return something;
}
const customPrototype = {
greeting: (name) => {
const greetingTemplate = `Hello ${name}`;
return greetingTemplate;
},
randomNumber: () => {
return Math.random();
},
};
// Extending prototype to access our custom prototype functions
Object.assign(foo, customPrototype);
console.log(foo()); // the thing
console.log(foo.greeting('People')); // Hello People
console.log(foo.randomNumber()); // 0.26138311987993545
// Default prototype functions are working as well
console.log(foo.toString()); // [object Function]
EDIT: Thanks to #Bergi for correcting me!
Check the below code, reference taken from Can you create functions with custom prototypes in JavaScript?
function MyFun() {
if (!this || this==window) {
return new MyFun();
}
var f = function() {
return "thanks for calling!";
}
f.__proto__ = MyFun.prototype;
f.constructor = MyFun;
return f;
}
MyFun.prototype = {
foo: function() {
return "foo:" + this();
},
__proto__: Function.prototype
};
var f = new MyFun();
alert("proto method:"+f.foo()); // try our prototype methods
alert("function method:"+f.call()); // try standard function methods
alert("function call:"+f()); // try use as a function
alert('typeof:' + typeof f); // "function", not "object". No way around it in current js versions
alert('is MyFun:' + (f instanceof MyFun)); // true
alert('is Function:' + (f instanceof Function)); // true

Javascript unable to delete a member property from a member function [duplicate]

This question already has answers here:
Methods in ES6 objects: using arrow functions
(6 answers)
Closed 2 years ago.
I have an object like this.
var v= {
a: 1,
delete: () => delete this.a,
}
I am not able to delete a after executing v.delete
You need convert arrow to function to use this keyword.
Also you did not call delete method to delete property.
var v= {
a: 1,
delete: function () {
delete this.a
}
}
v.delete()
console.log(v)
var v= {
a: 1,
delete: function(){delete this.a}
}
console.log("before=" + v.a)
v.delete()
console.log("after="v.a)
Arrow function doesn't have access to this context of the current object.

Object prototype can't access properties with `this` [duplicate]

This question already has answers here:
ES6 arrow functions not working on the prototype?
(4 answers)
Closed 5 years ago.
So, I saw several examples that this should work. But obviously, I'm missing something, because it doesn't. :/
Could somebody please explain to me what I'm doing wrong here? :)
function Code (b) {
this.b = b
this.arr = []
}
Code.prototype.add = (v) => {
console.log(this.b)
this.arr.forEach(element => {
console.log(element)
});
this.arr.push(v)
}
var c = new Code('bla')
console.log(c.add('asdf'))
So this throws an error with:
this.arr.forEach(element => {
^
TypeError: Cannot read property 'forEach' of undefined
Obviously, I'm doing something wrong here. But I don't know what.
Thanks!
Gergely.
function Code (b) {
this.b = b
this.arr = []
}
Code.prototype.add =function(v){
console.log(this.b)
this.arr.forEach(function(element){
console.log(element)
});
this.arr.push(v)
console.log(this.arr)
}
var c = new Code('bla')
console.log(c.add('asdf'))
You should use function(), instaed of () => arrow fucntion, since arrow function's this works differently.
this of an arrow function only refers to this that exists in the outer scope.
function Code (b) {
this.b = b
this.arr = []
}
Code.prototype.add = function(v) {
console.log(this.b)
this.arr.forEach(element => {
console.log(element)
});
this.arr.push(v)
}
var c = new Code('bla')
console.log(c.add('asdf'))

Why this.add is not a function in the object context [duplicate]

This question already has answers here:
What does "this" refer to in arrow functions in ES6?
(10 answers)
Arrow Function in Object Literal [duplicate]
(1 answer)
Closed 5 years ago.
In the following example I don't clearly understand why this.add is not defined. I suspect that it is because the arrows function are executed immediately and at the moment of compilation and the add function does not yet exist. Is this assumption correct? Or I'm missing something.
const arr= [1, 2, 3]
const squares = {
num: (arr) => {
return arr.map((x) => {
return (x * x) + this.add()
})
},
add: () => {
return 1
}
}
//TypeError: this.add is not a function
console.log(squares.num(arr))
You're using lexical this all the way out of the object. You'll need to avoid using an arrow function for num:
See documentation for arrow functions:
"An arrow function expression has a shorter syntax than a function expression and does not bind its own this..."
const arr = [1, 2, 3]
const squares = {
num: function(arr) {
return arr.map((x) => {
return (x * x) + this.add()
})
},
add: () => {
return 1
}
}
console.log(squares.num(arr))

Categories

Resources