我一直在摆弄代码来调用一个具有变量值名称的函数,然后在调用时保持 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完美运行:
通过简单地将函数分配给元素的 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/