附加到 DOMWindow 实例而不是自身实例的嵌套方法调用

Nested method call attached to an instance of DOMWindow instead of self

本文关键字:实例 嵌套 调用 方法 DOMWindow      更新时间:2023-09-26
someSingleton = (function() {    
    var someFunction = function() {
        console.log(this);
        someOtherFunc();
    };
    var someOtherFunc = function() {
        console.log(this);
    };
    return {
        method: someFunction
    }
})();
someSingleton.method();

如果运行这个,你会注意到第一个方法将按预期返回对象,第二个嵌套方法调用someOtherFunction将返回DOMWindow对象。

除了将实例(this(作为参数传递给第二个方法之外,我如何使第二个方法调用引用包含对象而不是DOMWindow。

someOtherFunc.call(this);

它仅取决于函数的调用方式,而不取决于函数的定义位置或方式。

您可以使用 call 方法 [MDN] 显式指定函数的调用上下文:

var someFunction = function() {
    console.log(this);
    someOtherFunc.call(this);
};

thiswindow 的错误绑定是一个常见的 JavaScript 错误。

理解JavaScript中的this可能是一个挑战。我可以推荐阅读 Douglas Crockford 的 Javascript: The Good Parts,以便更好地理解。同时,您可以查看此链接:)http://javascriptweblog.wordpress.com/2010/08/30/understanding-javascripts-this/

父对象分配给变量that是很常见的。这样,您可以通过它访问它的属性和函数:

(function(){
  var that = this;
  that.someFunc = function(){};
  that.someOtherFunc = function(){
    console.log(that);
  };
})();

一种常见的方法是使用 bind 函数来存储方法的上下文。一个简单的例子可能看起来像这样:

someSingleton = (function() {   
    var singleton = {};
    var _bind = function (func, me) {
        return function () {
            func.apply(me, arguments);   
        }
    }
    var someFunction = _bind(function() {
        console.log(this);
        someOtherFunc();
    }, singleton);
    var someOtherFunc = _bind(function() {
        console.log(this);
    }, singleton);
    singleton.method = someFunction;
    return singleton;
})();
someSingleton.method();​