标题的道歉,但没有简洁的方式。我正在研究下面的代码,它旨在将一组计数器链接在一起,形成一个大的代码。建立一个时钟或其他。将对象函数传递给对象构造函数
function subcounter(max, name, trigger) {
this.index = 0;
this.trigger = trigger;
this.name = name;
this.tick = function() {
this.index++;
if (this.index==max) {
this.index=0;
this.trigger();
}
}
this.show = function() {
alert(this.name+' triggered');
}
}
y = new subcounter(2,'y',function(){alert('finished')});
x = new subcounter(2,'x',y.tick);
for (var index = 0; index < 12; index++) {
alert ([x.index, y.index]);
x.tick();
}
这不起作用。为了调试我代替上面的一行:
x = new subcounter(2,'x',y.show);
而且发现,“X触发”显示,而不是“Y触发”,这是我所期望的。这里发生了什么? (在Firefox中试过)。
感谢您的回答或指向我的文档this
。然而,我的大脑仍然无法理解函数如何作用于一个对象实例:'y.show'可以在不同的对象实例上解析该函数。
的答案似乎是:
x = new subcounter(2,'x',function() {y.tick();});
但我仍想明白为什么预期原不起作用。
阅读'this':https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FOperators%2Fthis – haim770