2

変数の値の名前で関数を呼び出し、呼び出されたときに this スコープを保持するコードをいじっていますが、 this ポインターは、jQuery の bind メソッドではなく、使用した要素のコンテキストにあるようです呼び出している可能性のある関数が含まれているオブジェクトです。ここで問題を説明するためのいくつかのコードを明確にするために:

classname.prototype = {
    bindElementToFunction: function(element, functionToCall){
        $(element).bind("click", 
                        {realThis: this, functionToCall: functionToCall}, 
                        this.callFunction);
    },

    // I had hoped I could change the this pointer back to the object by running 
    // it through this function, I have tried using .apply and .call but I can't 
    // seem to get them to work with function pointers
    callFunction: function(event){
        var realThis = event.data.realThis;
        var functionToCall = event.data.functionToCall;
        functionToCall = realThis[functionToCall];
        // I have tried .apply and .call in several different ways but can't seem 
        // to get them to work in this context
        functionToCall(); 
    },
    abitraryFunction: function(){
        this.test();
    },
};

ここでの問題は、バインド関数からの要素をまだ参照している abitraryFunction まで、すべてが正常に機能することです。適切な this ポインターを使用して .apply() を実行しようとしましたが、機能していないようです。

では、関数ポインターと組み合わせて「this」ポインターのコンテキストを変更するにはどうすればよいですか? 「this」がメソッドが含まれるオブジェクトを参照しているオブジェクト内でメソッドを実行する要素にバインド関数を実行できる限り、私が書いたすべてのコードを自由に破棄してください。

ありがとう

4

1 に答える 1

1

jQuery バインドにより、コードが必要以上に複雑になっていると思います。JavaScriptbind()関数は完全に機能します。

http://jsfiddle.net/bQGWS/

要素の onclick (またはその他のイベント フック) に関数を割り当てるだけで、thisは要素の視点から評価され、要素自体を指します。

bind を使用すると、this渡された var に効果的に置き換えられた関数のコピーが作成されbind()ます。

classname = function(){}

classname.prototype = {
    method: function(){
        try {
            alert( this.othermethod() );
        } catch(e) {
            // Method doesn't exist in scope
            alert( 'Wrong scope :(');
        }
    },

    othermethod: function(){
        return 'hello desired scope!';
    },

    referenceToElement: function(elementId, functionname){
        var el = document.getElementById(elementId);

        // Just assigning the function as is
        el.onclick = this[functionname];
    },

    bindToElement: function(elementId, functionname){
        var el = document.getElementById(elementId);

        // Using the bind function to create a copy in the
        // scope of this (within the prototype)
        el.onclick = this[functionname].bind(this);
    }
}

var instance = new classname();
instance.referenceToElement('reference', 'method');
instance.bindToElement('bound', 'method');
于 2012-06-27T13:04:32.987 に答える