考虑以下Javascript类:
function ClassA() {
this.someVariable = someValue;
this.myHandler = function(){
// I WANT TO CALL InnerFunction
this.innerFunction();
};
this.innerFunction = function(){
// do something that accesses/manipulates someVariable
};
this.hookUp = function(id){
document.getElementById(id).onclick = this.myHandler;
};
};
...
...
var button = document.createElement('button');
button.setAttribute('id','mybuttonid');
// append button to the document
...
...
var x = new ClassA();
x.hookUp('mybuttonid');
当我单击按钮时,处理程序将执行,但是,“this”现在引用按钮元素而不是ClassA对象,因此它无法解析innerFunction()。
我需要的是一种向处理程序指示此上下文是ClassA实例的方法(类似于$ .ajax({context:this ....}),您可以在其中使用'this'。 done()或.error()处理程序),或一种将实例的引用传递给处理程序的方法,而无需使处理程序在实例化时执行。例如,如果我尝试将'this'作为首选参数传递给myHandler(myHandler = function(ref){},然后更改:document.getElementById(id).onclick = this.myHandler(this);)
但是,当您向myHandler添加参数时,该函数在类实例化时而不是在单击时执行。
任何帮助将不胜感激。
最佳答案
更换...
this.myHandler = function(){
this.innerFunction();
};
...与...
var self = this;
this.myHandler = function() {
self.innerFunction();
};
参见this article by Crockford。引用:
另请参阅What does 'var that = this;' mean in JavaScript?