I found the following code in this site (excluding console.log stuff):
console.log((function(x, f = () => x) {
var x;
// console.log(this.x,x); // undefined 1
var y = x;
x = 2;
return [x, y, f()];
})(1)); // [2, 1, 1]
Apparently f() having the same result as x which are being passed in parameter. And if you uncomment console.log(this.x,x) it would show undefined and 1.
I've read the following:
What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?
What is the difference between () => {} and function() {} in react-native javascript?
What are the differences (if any) between ES6 arrow functions and functions bound with Function.prototype.bind?
What does this refer to in a JavaScript function?
How does the "this" keyword work?
this - JavaScript | MDN
My question is why did this.x return undefined even if you set the var x = 2? Refer to the following snippet:
console.log((function(x, f = () => x) {
var x = 2;
console.log(this.x,x); // undefined 2
var y = x;
x = 2;
return [x, y, f()];
})(1)); // [2, 2, 1]
and if you remove var x
console.log((function(x, f = () => x) {
console.log(this.x,x); // undefined 1
var y = x;
x = 2;
return [x, y, f()];
})(1)); // [2, 1, 2]
does this.x doesn't point to the parameter or local variable?
From the book You don't know JS by Kyle Simpson
this is actually a binding that is made when a function is invoked, and what it references is determined entirely by the call-site where the function is called.
There are 4 rules to follow if you want to figure out what this is referring to
Called with new? Use the newly constructed object.
Called with call or apply (or bind)? Use the specified object.
Called with a context object owning the call? Use that context object.
Default: undefined in strict mode, global object otherwise.
Here, this refers to the global object, that's why this.x is undefined.
If you want to enforce it, you can use bind.
In case you want to learn more about all the technicalities you should read this
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With