How to use this in ES6 arrow function?
brief introduction: this in the arrow function is different from the function defined by the general function. The definition of this in the arrow function: this is bound when the function is defined, not when the function is executed.
(1) The general function this points to binding when executing. 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 outputs 22(2) so-called definition time binding, that is, this is inherited from the parent execution context! ! This in, for example, this.x in the arrow function here, the arrow function itself is 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 this.x here 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. Similarly:
(3)
var a = 11 function 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(); //It's strange to output 22, right? I understand it this way. The specific meaning of binding this when defined in ES6 should inherit this in the parent execution context, and it should not be the parent execution context! ! ! In this way, the unclear pointing in many arrow functions is solved.
note: simple objects (non-functions) have no execution context!
To deeply understand this
in the arrow function, the fixation of this point is not because there is a mechanism to bind this inside the arrow function, but the actual reason is that the arrow function does not have its own this at all, resulting in that the internal this is the external code block's this. Because it has no this, it cannot be used as a constructor.
we can simulate the arrow function transformation in ES5:
//es6functionfoo () {
settimeout (() = > { console.log('id:', this.id);
}, 1);
}
// ES5function foo() { var _this = this; setTimeout(function () { console.log('id:', _this.id);
}, 1);
} Therefore, when defining an object, define its attributes, where this generally refers to the global situation or this in the environment where the object is located.
I believe that after reading these cases, you have mastered the methods. Please pay attention to other related articles on Gxl!
Related reading:
Summarize python Django's experience in development
ES6 module Syntax Loading import export
How to use getBoundingClient () to realize the scroll fixation of div container.