【发布时间】:2013-11-06 14:16:24
【问题描述】:
考虑以下 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()。
我需要一种方法来向处理程序表明 this 的上下文是 ClassA 的实例(类似于 $.ajax({context: this....}) ,您可以在其中使用“this”在 .done() 或 .error() 处理程序中),或者一种将实例的引用传递给处理程序而不使处理程序在实例化时执行的方法。例如,如果我尝试将“this”作为参数传递给 myHandler(myHandler=function(ref){},然后更改:document.getElementById(id).onclick = this.myHandler(this);) 但是当您向 myHandler 添加参数时,该函数会在类实例化时执行,而不是在单击时执行。
任何帮助将不胜感激。
【问题讨论】:
-
尝试使用
var someVariable而不是this.someVariable。someVariable仅在函数范围内可用,因此不需要this。此外,JavaScript 中没有类之类的东西,因此您使用this的想法可能会被误导。 -
谢谢..也许我不是很清楚,我的主要问题是访问 innerFunction()。我正在尝试编写类似于 OO 的代码,以便更容易理解和维护,至少对我来说:)。
标签: javascript class javascript-objects