通过变量值调用函数并保持此指针的范围

时间:2012-06-27 12:05:28

标签: javascript this function-pointers

我一直在摆弄代码来调用一个带有变量值名称的函数,然后在调用时保持这个范围,但是这个指针似乎是在我使用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,这仍然是指绑定函数中的元素。我已尝试使用适当的指针执行.apply(),但它们似乎不起作用。

所以这里的问题是如何结合函数指针更改“this”指针的上下文? 请尽可能废弃我编写的所有代码,只要我能够对一个元素执行绑定功能,然后在一个对象中运行一个方法,其中“this”是对该方法所在的对象进行的。

由于

1 个答案:

答案 0 :(得分:1)

我认为jQuery绑定使你的代码变得比它需要的更复杂。 JavaScript bind() function完美无缺:

http://jsfiddle.net/bQGWS/

通过简单地为元素的onclick(或任何其他事件挂钩)分配函数,this从元素的角度进行评估,因此指向元素本身。

使用bind时,最终会得到一个函数的副本,其中this被有效替换为传递给bind()的var。

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');