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

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

    return {
        method: someFunction
    }
})();

someSingleton.method();

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

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

4

4 回答 4

1

someOtherFunc.call(this);

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

于 2012-07-13T20:52:38.197 回答
0

一种常见的方法是使用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();​
于 2012-07-13T21:01:32.720 回答
0

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

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

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

于 2012-07-13T20:54:31.533 回答
0

理解thisjavascript 可能是一个挑战。我可以推荐阅读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);
  };
})();
于 2012-07-13T20:57:24.843 回答