繁体   English   中英

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

[英]Calling function by value of variable and keeping scope of this pointer

我一直在摆弄代码以变量值的名称调用函数,然后在调用时保留此范围,但是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仍在引用bind函数中的元素为止。 我尝试使用适当的this指针执行.apply(),但它们似乎不起作用。

因此,这是一个问题,如何与函数指针一起更改“ this”指针的上下文? 只要我能够对元素执行绑定功能,然后再在对象中运行一个方法(其中“ this”与该方法所在的对象相对应),便可以随意废弃我编写的所有代码。

谢谢

我认为jQuery绑定使您的代码变得比需要的复杂。 JavaScript bind()函数可以完美运行:

http://jsfiddle.net/bQGWS/

通过简单地将功能分配给元素的onclick(或任何其他事件挂钩), this可以从元素的角度对其进行评估,因此可以指向元素本身。

当您使用绑定,你最终与功能的副本,其中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');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM