Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is wrong with this.variable in a function return undefined [duplicate]

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?

like image 671
Shinjo Avatar asked Nov 20 '25 02:11

Shinjo


1 Answers

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

  1. Called with new? Use the newly constructed object.

  2. Called with call or apply (or bind)? Use the specified object.

  3. Called with a context object owning the call? Use that context object.

  4. 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

like image 60
soueuls Avatar answered Nov 21 '25 16:11

soueuls



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!