Arrows point to function in this

After the project is done recently encountered a problem error when using this function in the arrow, the arrow function of the wording change function (), this point was as expected. Look on this issue deserves.

In the era before the arrow ES5 function appears, this points to its caller . Which object to call this property or method, this points to the object. It's a bit like the "I" of personal pronouns, who is from the mouth to say, "I", the "I" to refer to whom.

A simple example:

// 用var定义的变量,this指向window
// 调用sayName()等于调用this.sayName()等于调用window.sayName()
var name = 'window';
var sayName = function(){
  return this.name
}
console.log(sayName())          //window
console.log(this.sayName())     //window
console.log(window.sayName())   //window

// 用obj调用的sayName方法,其中this指向调用它的obj
var obj = {
  name : 'obj',
  sayName : function(){
    return this.name
  }
}
console.log(obj.sayName())      //obj

Later, the arrow function inside this ES6 specification is to define it binding upon, pointing to its parent scope, instead of calling it an object , that this point can not be changed by the call and apply.

Arrow object literal function of this point:

// 用var定义的变量,this指向window
// 虽然展现结果和上例一样,但是this的指向绑定的时机是有区别的,箭头函数在定义时已经绑定,普通函数只会在调用时确定
var name = 'window';
var sayName = () => {
  return this.name;         //this指向window
};
console.log(sayName());         //window
console.log(this.sayName());    //window
console.log(window.sayName());  //window

//同样用obj调用的sayName方法,this指向父级作用域window
var obj = {
  name: 'obj',
  sayName: () => {
    return this.name;  
  }
};
console.log( obj.sayName() );     //window
console.log( obj.sayName() === window.sayName() );     //true

This is a function of the arrow pointing in this object literal in behavior. Say one more thing, when invoked with the instance of the object will be different.

See the examples below:

var name = 'window'
    
function Obj(name){     //构造函数Obj
  this.name = name;
  this.s1 = function(){
    return this.name;   //普通函数方法,this指向Obj
  }
  this.s2 = () => {
    return this.name;   //箭头函数方法,this还是指向Obj,因为构造函数function Obj(name)形成了一级作用域
  };
}
Obj.prototype.s3 = function(){
  return this.name;     //原型链上的普通方法,this指向实例obj1的构造函数Obj
}
Obj.prototype.s4 = () => {
  return this.name;     //原型链上的箭头函数,定义它的时候,这个箭头函数的父级作用域是window
}

//实例化对象
const obj1 = new Obj('obj');

console.log(obj1.s1());  //obj
console.log(obj1.s2());  //obj
console.log(obj1.s3());  //obj
console.log(obj1.s4());  //window
  • S2 () function to find the arrow 定义它时的父级scope, because the constructor functions Obj is, it forms its own scope. Defined S2 () when父级作用域变成了构造函数Obj所在的域
  • S4 difference () and S2 () is S4 () mounted to the constructor of the prototype, 定义s4()的时候,这个箭头函数的父级作用域是windowso by calling the method of Example outputs a 'window'

Guess you like

Origin www.cnblogs.com/sonicwater/p/12028929.html