This time I will show you where this in the ES6 arrow function points to, and what are the precautions for using this in the ES6 arrow function. The following is a practical case, let's take a look.
Brief introduction: this in the arrow function points to a function defined differently from the general function. The definition of this in the arrow function: this in the arrow function is bound whendefining the function. Instead of binding when executing the function.
(1) Generally, the function this points to is bound during execution. When running obj.say(), this points to theobject of obj.
var x=11; var obj={ x:22, say:function(){ console.log(this.x) } } obj.say(); //console.log输出的是22
var x=11; var obj={ x:22, say:()=>{ console.log(this.x); } } obj.say(); //输出的值为11
var a=11 function test1(){ this.a=22; let b=function(){ console.log(this.a); }; b(); } var x=new test1();
var a=11; function test2(){ this.a=22; let b=()=>{console.log(this.a)} b(); } var x=new test2(); //输出22
Note: Simple objects (non-functions) have no execution context!
In-depth understanding of this in the arrow function
In the arrow function, the fixation of this point is not because of the internal arrow function There is a mechanism to bind this. The actual reason is that the arrow function does not have its own this at all, so the internal this is the this of the outer code block. Precisely because it does not have this, it cannot be used as aconstructor.
We can simulate the arrow function conversion in ES5:// ES6 function foo() { setTimeout(() => { console.log('id:', this.id); }, 100); } // ES5 function foo() { var _this = this; setTimeout(function () { console.log('id:', _this.id); }, 100); }
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website! Recommended reading:
How to change the status of radio using JS
How to set bootstrap table to height percentage
The difference between var foo = function () {} and function foo()
The above is the detailed content of Where does this in ES6 arrow functions point to?. For more information, please follow other related articles on the PHP Chinese website!