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

bindを使用します。

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 に答える