Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
188 views
in Technique[技术] by (71.8m points)

javascript - arrow function and this

I'm browsing twitter and found this tweet:

https://twitter.com/_ericelliott/status/855598297939144704

Here is the code from the tweet:

const double = () => this.x * 2;
const numDouble = double.bind({ x: 5 });
numDouble();

When you run this snippet in console it'll produce NaN. How? Author is explicitly binding the value of x, but still it's showing NaN.

Author is also specifying that arrow function can't bind this. As i know that arrow function lexically bind the value of this form surrounding scope. Then why author is claiming so?

Please clarify my doubts and Thanks in advance for the help.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Arrow functions don't bind this. As per MDN:

No binding of this

Until arrow functions, every new function defined its own this value (a new object in the case of a constructor, undefined in strict mode function calls, the context object if the function is called as an "object method", etc.). This proved to be annoying with an object-oriented style of programming.

So this in your example will be the global object window which apparently don't have a property called x.

Example:

function foo() {
  let arrow = () => {
    console.log(this);     // will use foo's this as arrow will never have its own this
  }
  
  arrow.call({"x": "x"});  // ... even if we specify it using bind, call, or apply
}

foo.call({"y": "y"});      // specifying the this for foo (this value will eventually be used by arrow because it will be availbale in its scope)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...