For this problem in the ES6 arrow function, the es6 arrow function this
Brief Introduction: this in Arrow functions points to different functions defined by general functions. this in Arrow functions is defined by this when defining functions, instead of binding when executing a function.
(1) In general, the function this points to the execution of the object. When running obj. say (), this points to the object obj.
Var x = 11; var obj = {x: 22, say: function () {console. log (this. x)} obj. say (); // console. log output is 22
(2) Binding in definition means that this is inherited from the parent execution context !! Such as this in the arrow function. x, the arrow function itself and the say level are in the form of key: value, that is, the object where the arrow function itself is located is obj, and the parent execution context of obj is window, so here this. x actually represents window. x, so the output is 11.
Var x = 11; var obj = {x: 22, say :() => {console. log (this. x) ;}} obj. say (); // the output value is 11.
Similar:
(3)
var a=11function test1(){ this.a=22; let b=function(){ console.log(this.a); }; b();}var x=new test1();
Output 11
Arrow functions:
Var a = 11; function test2 () {this. a = 22; let B = () => {console. log (this. a)} B ();} var x = new test2 (); // output 22
It's strange, right? I understand this. The specific meaning of binding this in ES6 should inherit this in the parent execution context, do not use the parent execution context !!! In this way, the points in many arrow functions are not clear and can be solved.
Note: Simple objects (non-Functions) have no execution context!
In-depth understanding of this in Arrow Functions
In the arrow function, this is not fixed because the arrow function has a mechanism to bind this internally. The actual reason is that the arrow function does not have its own this, as a result, this is the outer code block. Because it does not have this, it cannot be used as a constructor.
We can simulate the arrow Function Conversion in ES5:
// ES6function foo() { setTimeout(() => { console.log('id:', this.id); }, 100);}// ES5function foo() { var _this = this; setTimeout(function () { console.log('id:', _this.id); }, 100);}
Therefore, when defining an object, define the object property. this in it points to the global condition, or this in the environment where the object is located.
Summary
The above section describes this in the ES6 arrow function. I hope it will help you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!