whitejy / learn

学习使用
0 stars 0 forks source link

this指向 #11

Open whitejy opened 5 years ago

whitejy commented 5 years ago

1、setTimeout & setInterval 对于延时函数内部的回调函数的this指向全局对象window(当然我们可以通过bind方法改变其内部函数的this指向)

function Person() {  
    this.age = 0;  
    setTimeout(function() {
        console.log(this);
    }, 3000);
}

var p = new Person();//3秒后返回 window 对象

2、箭头函数的this

var adder = {
  base : 1,

  add : function(a) {
    var f = v => v + this.base;
    return f(a);
  },

  addThruCall: function inFun(a) {
    var f = v => v + this.base;
    var b = {
      base : 2
    };

    return f.call(b, a);
  }
};

console.log(adder.add(1));         // 输出 2
console.log(adder.addThruCall(1)); // 仍然输出 2(而不是3,其内部的this并没有因为call() 而改变,其this值仍然为函数inFun的this值,指向对象adder

作为方法的箭头函数this指向全局window对象,而普通函数则指向调用它的对象

var obj = {
  i: 10,
  b: () => console.log(this.i, this),
  c: function() {
    console.log( this.i, this)
  }
}
obj.b();  // undefined window{...}
obj.c();  // 10 Object {...}

总结:箭头函数中的this是指向父级的执行上下文。 即上面的例子,父级为obj对象,而obj对象的执行上下文为windows对象

参考:https://www.cnblogs.com/dongcanliang/p/7054176.html https://blog.csdn.net/liwusen/article/details/70257837