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 does this refer to in a JavaScript function?
How does the "this" keyword work?
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?