我无法围绕特定的“ this”绑定

时间:2019-03-02 14:52:39

标签: javascript

var obj = {
  log: function() {
    console.log(this);
    var nestedLog = function() {
      console.log(this);
    }
    nestedLog();
  }
};

obj.log();
.as-console-wrapper { max-height: 100% !important; top: 0; }

然后我得到

{log: ƒ}
Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}

有人可以解释为什么this绑定消失了吗?我没有从全局执行上下文执行nestedLog,但是仍然从window绑定中获得了this对象。我真的不明白为什么会这样。我知道this绑定取决于执行上下文以及我是否这样做:

var log = obj.log;
log()

很明显,我得到了window对象。但是当我在nestedLog函数中执行obj.log时,this绑定不应该保持不变吗?有人可以解释一下它是如何工作的吗?

1 个答案:

答案 0 :(得分:0)

logobj的方法,因此将其设置为obj

  

将函数作为对象的方法调用时,其this设置为在其上调用方法的对象

nestedLog不是对象方法,因此将this设置为window对象
在函数的simple call

  

this将默认为全局对象,该全局对象在浏览器中为window

使用可以使用Arrow Function

来解决此问题

var obj = {
  log: function() {
    console.log(this);
    var nestedLog = () => {
      console.log(this);
    }
    nestedLog();
  }
};

obj.log();
.as-console-wrapper { max-height: 100% !important; top: 0; }