按变量的值调用函数并保持此指针的作用域

Calling function by value of variable and keeping scope of this pointer

本文关键字:指针 作用域 变量 值调用 函数      更新时间:2023-09-26

我一直在摆弄代码来调用具有变量值名称的函数,然后在调用时保留 this 作用域,但 this 指针似乎在我使用 jQuery 的绑定方法的元素的上下文中,而不是我可能调用的函数所在的对象。为了澄清这一点,这里有一些代码来说明这个问题:

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"引用该方法所在的对象。

谢谢

我认为

jQuery绑定使您的代码比需要的更复杂。JavaScript bind()函数完美运行:

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