Javascript - 范围在回调中丢失

时间:2012-10-29 18:23:57

标签: javascript

我有以下代码:

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范围可用的最佳方法是什么?

3 个答案:

答案 0 :(得分:6)

使用bind

this.callback = function(){
    this.doSomethingUseful(); // doesn't work
}.bind(this);

答案 1 :(得分:2)

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

var foo = 'bar';
function(){
  // this = 'bar';
}.call(foo);

答案 2 :(得分: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);