我使用 SWFAddress 深度链接我的网站(链接到 SWFAddress)。我喜欢将代码分解为类,因此我的主要结构类似于:
function SomeClass() {
// This adds the this.handleChange() function to the
// SWFAddress event listener
this.initializeSWFA = function() {
// SWFAddress variable is instantiated in SWFAddress javascript file
// so I can use it here
SWFAddress.addEventListener(SWFAddressEvent.CHANGE, this.handleChange);
}
// SWFAddress is supposed to call this function
this.handleChange = function(evt) {
// Some code here
}
}
// Instantiate the SomeClass
var someVar = new SomeClass();
someVar.initializeSWFA();
这条线在这里不起作用:
SWFAddress.addEventListener(SWFAddressEvent.CHANGE, this.handleChange);
我尝试将其更改为:
SWFAddress.addEventListener(SWFAddressEvent.CHANGE, this.handleChange());
或者
var self = this;
SWFAddress.addEventListener(SWFAddressEvent.CHANGE, self.handleChange);
这些也不起作用。
那么在这种情况下如何从类中引用 JavaScript 函数呢?
如果函数handleChange
在类之外,我可以写下函数的名称。
首先,谢谢大家的回答。我仍在试图弄清楚这一切在 JavaScript 中是如何工作的。我不习惯 JavaScript 中的面向对象模型。
这是目前的解决方案。我仍然无法弄清楚如何在 JavaScript 中很好地做到这一点,但这个解决方案有效。我尝试实施 ehudokai 建议的解决方案(谢谢),但是我无法使其工作。
function SomeClass() {
// This adds the this.handleChange() function to the
// SWFAddress event listener
this.initializeSWFA = function() {
// SWFAddress variable is instantiated in SWFAddress javascript file
// so I can use it here
SWFAddress.addEventListener(SWFAddressEvent.CHANGE, someFunc);
}
// SWFAddress suppose to call this function
this.handleChange= function(evt) {
// Some code here
}
}
// Instantiate the SomeClass
var someVar = new SomeClass();
function someFunc(evt) {
someVar.handleChange(evt);
}
someVar.initializeSWFA();
我不喜欢这样,因为这涉及定义一个额外的函数,因此如果有人弄清楚如何从 JavaScript 对象向 SWFAddress EventListener 添加方法,则需要额外的空间。请帮帮我。