【发布时间】:2012-09-03 19:50:36
【问题描述】:
在下面的代码 sn-p 中,'this.x()' 只能在情况 2 中调用(参见 main())。 同样 Bar 在情况 1 中不等于此值,但在情况 2 中等于。
function Class_Bar() {
this.panel = null;
this.init = function () {
// do some stuff
this.panel = 20;
}
this.apply = function () {
alert(Bar == this);
Bar.x();
this.x();
}
this.x = function() {
alert("Some friendly message");
alert(Bar.panel);
}
}
var Bar = new Class_Bar();
function Class_Factory() {
this.factories = new Array();
this.add = function (init, apply) {
this.factories.push({"init":init, "apply":apply});
}
this.init = function () {
for (var i = 0; i < this.factories.length; ++i) {
this.factories[i]["init"]();
}
}
this.apply = function () {
for (var i = 0; i < this.factories.length; ++i) {
this.factories[i]["apply"]();
}
}
}
var Factory = new Class_Factory();
function main() {
// Case 1
Factory.add(Bar.init, Bar.apply);
Factory.init();
Factory.apply();
// Case 2
Bar.init();
Bar.apply();
}
main();
任何想法如何“修复”/解决此行为?
我找到了一个可能的解决方案,但它似乎是一个“糟糕”的 hack。:Javascript: How to access object member from event callback function
【问题讨论】:
-
如果我是你,我会考虑将对象本身传递给工厂,在你试图做的事情的背景下更有意义。
标签: javascript arrays object callback