按变量的值调用函数并保持此指针的作用域
Calling function by value of variable and keeping scope of this pointer
我一直在摆弄代码来调用具有变量值名称的函数,然后在调用时保留 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');
相关文章:
- 监视函数从服务返回不起作用,但作用域函数起作用
- 将作用域存储在JSON中
- 从控制器继承了隔离的作用域以生成可重用的指令
- 从ng模板访问作用域
- 调用私有作用域
- 对父作用域的指令更新延迟了一步
- 正在$rootScope上达到控制器作用域$在内部控制器上
- 两个指令创建新的继承的和隔离的作用域-元素得到哪个
- 这两个关于 JavaScript 作用域链的例子有什么区别?
- 在具有命名作用域的自定义Polymer元素中隐藏表行
- AngularJS指令隔离作用域
- Angularjs:修改js中的作用域,稍后在页面中使用
- 访问多个指令的隔离作用域
- Javascript作用域和Ajax调用;工作不正常
- 向Angular作用域对象添加对象数组——TypeError
- ng重复中的ng模型-初始化唯一作用域属性
- 在put方法之前从作用域获取数据
- 按变量的值调用函数并保持此指针的作用域
- j在 AJAX 中调用函数时查询此指针作用域
- JavaScript函数指针作用域