javascript - 通过变量值调用函数并保持此指针的作用域

标签 javascript this function-pointers

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

所以这里的问题是如何结合函数指针更改“this”指针的上下文? 随意废弃我编写的所有代码,只要我能够对元素执行绑定(bind)函数,然后在对象内运行方法,其中“this”引用该方法所在的对象。

谢谢

最佳答案

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

http://jsfiddle.net/bQGWS/

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

当您使用 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');

关于javascript - 通过变量值调用函数并保持此指针的作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11225781/

相关文章:

javascript - jquery 的 $.ajax 成功中的 'this' 指的是什么?

javascript - 提取链接 ID 以在 jquery 函数中使用

javascript - 可重用函数中的“this”绑定(bind)?

c++ - 收到错误 : no match for operator[] in

C++:具有指向函数的指针作为属性的类

javascript - 如何在javascript中访问对象属性?

javascript - 返回数组中出现次数最多的单词

javascript - 如何等待函数在for循环js中完成?

c++ - 指向成员函数的指针

javascript - d3js svg 水滴或泪滴