標題的道歉,但沒有簡潔的方式。我正在研究下面的代碼,它旨在將一組計數器鏈接在一起,形成一個大的代碼。建立一個時鐘或其他。將對象函數傳遞給對象構造函數
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