我一直在摆弄代码来调用具有变量值名称的函数,然后在调用时保持 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”引用该方法所在的对象的对象中运行方法。
谢谢