4

我有以下代码:

var myPage = {};
myPage.component = function(callback){

    var somethingHappened = true;

    if (somethingHappened){
        callback();
    }
};

myPage.main = function(){

    // Initialise.
    this.init = function(){

        // make an instance of my component
        this.component = new myPage.component( this.callback );

        // need my utility function here
        this.doSomethingUseful();
    };

    // Callback to be executed when something happs in the component.
    this.callback = function(){
        this.doSomethingUseful(); // doesn't work
    };

    // A useful utility that needs to be accessible from both the 
    // init() and callback() functions
    this.doSomethingUseful = function(){
        // some utility stuff
    };
};
new myPage.main().init();

当从组件执行回调函数时,确保 myPage.main 范围可用的最佳方法是什么?

4

3 回答 3

7

使用绑定

this.callback = function(){
    this.doSomethingUseful(); // doesn't work
}.bind(this);
于 2012-10-29T18:25:33.467 回答
2

如果要提供范围,可以使用Function.prototype.call.

var foo = 'bar';
function(){
  // this = 'bar';
}.call(foo);
于 2012-10-29T18:26:52.677 回答
0

使用此函数实例化对象:

function newClass(klass) {
    var obj = new klass;

    $.map(obj, function(value, key) {
        if (typeof  value == "function") {
            obj[key] = value.bind(obj);
        }
    });

    return obj;
}

这将自动绑定所有函数,因此当对象内部的方法具有其对象的上下文时,您将以习惯 OOP 样式获取对象。

所以你实例化你的对象不是通过:

var obj = new myPage();

但:

var obj = newClass(myPage);
于 2014-12-06T16:24:23.153 回答