Javascript "this" 当回调是对象方法时的上下文

Javascript "this" context when the callback is an object method

我有两个对象:myapp 和 dom。 plunker 上的代码取自(但略有简化)Stoyan Stefanov 的书 "Javascript patterns".

http://plnkr.co/edit/FutgitMBlnrYfBKuL0Ig?p=preview

var myapp = {};
var color = "purple";
myapp.color = "green";
var dom = {};
dom.color = "red";

myapp.paint = function (node) {
    console.log(this.color);
};


dom.findNodes = function (callback) {
    if (typeof callback === "function") {
        callback();
    }
}


dom.findNodes(myapp.paint);

据书:

If you call findNodes(myapp.paint), it won’t work as expected, because this.color will not be defined. The object this will refer to the global object, because findNodes() is a global function. If findNodes() were a method of an object called dom (like dom.findNodes()), then this inside of the callback would refer to dom instead of the expected myapp.

在我的代码中,我希望获得颜色 "red",因为我调用对象方法 dom.findNodes 而不是全局函数。那么为什么我总是得到一个值为 "purple" 的全局变量?谢谢!

这个函数:

function (callback) {
    if (typeof callback === "function") {
        callback();
    }
}

… 不使用 this 所以不管你叫它 findNodes 还是 dom.findNodes.

你关心的this在这里:

myapp.paint = function (node) {
    console.log(this.color);
};

当您调用 myapp.paint() 时,thismyapp

当您调用 callback() 时,thiswindow(在浏览器中,当不处于严格模式时)。

您可以像这样绑定 "this" 对象:

dom.findNodes(myapp.paint.bind(this));

或者假设这是一个参数并用它调用绘画函数:

dom.findNodes = function ( callback, thisObject )
{
    if (typeof callback === "function")
    {
        callback.call(thisObject);
    }
}

dom.findNodes(myapp.paint, myapp);