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

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))

Related

Declare function with property in one statement? [duplicate]

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);

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.

ES6 Function declaration difficulty [duplicate]

This question already has answers here:
Curly Brackets in Arrow Functions
(3 answers)
What does the arrow function with a () after means? [duplicate]
(3 answers)
Closed 4 years ago.
I am taking a course on React Native and realize that the instructor declares functions in two different ways, for seemingly no different reasons. Please explain when each function declaration should be used:
example = () => ();
vs
example = () => {};
Thank you
Arrow functions can differ in function bodies (Thanks Robbie). The concise function body can only consist of a single expression which is evaluated and implicitly returned. The conventional block function body requires the return keyword or it will return void.
example1 = () => 1 + 1;
example2 = () => {
const result = 1 + 1;
return result;
};
example3 = () => {
const result = 1 + 1;
};
example1() has a concise body and will implicitly return the result of the expression 2.
example2() has a block body and does explicitly return 2.
example3() has a block body and no explicit return, therefore it returns void.
Note that the normal braces () around a concise function body are required if you want to return an object literal:
example = () => ({some: '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'))

What is the meaning of (0, someFunction)() in javascript [duplicate]

This question already has answers here:
(1, eval)('this') vs eval('this') in JavaScript?
(4 answers)
Closed 6 years ago.
The community reviewed whether to reopen this question 3 months ago and left it closed:
Original close reason(s) were not resolved
I found this code in someone's code, it sound like this:
(0, function (arg) { ... })(this)
After I try to play around like below,
(0, function (arg) { console.log(arg) })(2);
console.log((0, 1, 2, 3));
(0, function plus1 (arg) { console.log(arg + 1) }, function plus2 (arg) { console.log(arg + 2) })(5);
I found that it will always return last item in the bracket.
I wonder what is the name of this programming pattern and what is the use case?
In this particular case it seems superfluous, but sometimes this approach is useful.
For example, with eval:
(function() {
(0,eval)("var foo = 123"); // indirect call to eval, creates global variable
})();
console.log(foo); // 123
(function() {
eval("var bar = 123"); // direct call to eval, creates local variable
})();
console.log(bar); // ReferenceError
It's also useful when you want to call a method without passing the object as the this value:
var obj = {
method: function() { return this; }
};
console.log(obj.method() === obj); // true
console.log((0,obj.method)() === obj); // false
Also note that, depending on the context, it might be the arguments separator instead of a comma operator:
console.log(
function(a, b) {
return function() { return a; };
}
(0, function (arg) { /* ... */ })(this)
); // 0
In this scenario, (0, function (arg) { /* ... */ }) are the arguments (a=0, b=function (arg) { /* ... */ }) to the function
function(a, b) {
return function() { return a; };
}
rather than the comma operator. (Then, the (this) at the end is function call with argument this to the returned function function() { return a; }. But this part is not relevant to the comma operator/argument separator difference)
It is a comma operator wrapped with a self-executing anonymous function. However, I have no idea as to why the meaningless 0 was included except for obfuscation purposes.
typical example could be,
for(var i=0,j=10; i < j; i++){
// code ...
}
comma operator would evaluate expressions from left-to-right and return result of right most expression
// e.g.
var a = 1, b= 2, c = 3, d = function(){ console.log("a => " + a) }()

Categories

Resources