and this refers to => Function

ES6 added a function arrow

The following is a comparison of the javaScript ES6 and before the function declaration, something return takes only one line or less when using the arrow function more elegant;

Before we declare the following function

function Fn = var (A, B) {
return A + B;
};
Fn (1,2); //. 3
for ES6 declare functions as follows

// where a and b are parameter passing, a + b can be interpreted as a + b return;
var Fn = (a, b) => a + b;
Fn (1,2); //. 3
// if not if required parameter passing
var fn = () => 3 ;
comes this point when this function and the arrow pointing ordinary function is not the same,

=> This is a point to point to define this object will not change. this points to the object of the calling function

function this function when the statement () point to point to the object which you are using. => Pointing to parent objects and more objects until the point windown, he does not point to the same level objects

function timer(){
this.age = 18;
var _this = this;
setTimeout(function(){
console.log(this);//指向了全局window
console.log(this.age);//undefined
console.log(_this.age);//18
},1000);

setTimeout(()=>console.log(this.age),1500);//18
};

var timer2 = new timer();

window.age = "nonono";
 
原文链接:https://blog.csdn.net/qq_41463701/article/details/82749479

Guess you like

Origin www.cnblogs.com/qhantime/p/11323736.html