JavaScript - "this" 在调用 Promises 而不是函数时不起作用

JavaScript - "this" doesn't work when calling Promises instead of functions

所以,我最近在开发库时遇到了一个很奇怪的问题,safe_children

当我写例子的时候,我决定尝试这样写:

var child = new Child('otherFile.js', 3 * 60);
child.loadScript()
  .then(child.spawn);

此代码无效。 this 指向一些我找不到的东西。但是,这段代码有效:

var child = new Child('otherFile.js', 3 * 60);
child.loadScript()
  .then(function(){
    child.spawn();
  });

有人知道为什么吗? this 在这种情况下是什么?谢谢!

您的问题与承诺无关。

您正在传递 child.spawn,这只不过是一个函数。你的 promise 没有办法知道它属于 child,所以它所能做的就是调用它。因此,this 很可能是 nullundefinedwindow 对象。

您可以通过执行以下操作看到相同的行为:

var sp = child.spawn;
sp();    // <---- `this` is not `child` here

您可以通过以下方式解决此问题:

.then(child.spawn.bind(child));

或者通过做你已经做过的事情。