2013-07-23 308 views
1

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

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();}); 

但我仍想明白爲什麼預期原不起作用。

+0

閱讀'this':https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FOperators%2Fthis – haim770

回答

2

應該是這樣

function subcounter(max, name, trigger) { 
    var that = this; 
    this.index = 0; 
    this.trigger = trigger; 
    this.name = name; 

    this.tick = function() { 
     that.index++; 
     if (that.index==max) { 
      that.index=0; 
      that.trigger(); 
     } 
    } 

    this.show = function() { 
     alert(that.name+' triggered'); 
    } 
} 

否則JavaScript的本地作用域將有this包含對外部情境this參考(即,你的情況x.this)的內部函數。

Here是一篇詳細介紹javascript本地範圍功能的文章,但這只是我得到的第一個結果,這是一個很常見的問題。

+0

我很樂意接受這個答案。除非它不起作用。我仍然'x觸發'。 –

+0

很奇怪:我用我的修改過的代碼(和'alert's替換爲'console.log')在http://jsfiddle.net/H5Bs3/創建了一個小提琴,它似乎在工作。 – Raibaz

+0

我看到那裏是正確的。但是Firefox/IE都工作不正確。 –

1

從我所看到的,它具有與「本」的價值將是一個函數裏面做什麼。

函數'this'的內部將是調用函數的對象的值。

當你調用this.trigger()時,它現在是對象'x'。因此,觸發功能,即「秀」,

this.name will be same as x.name 

爲了獲得在y對象的值,通過「Y」對象本身並調用來自該對象的顯示功能內。

function subcounter(max, name, trigger, methodName) { 
    this.index = 0; 
    this.trigger = trigger; 
    this.name = name; 

    this.tick = function() { 
     this.index++; 
     if (this.index==max) { 
      this.index=0; 
      this.trigger[methodName](); 
     } 
    } 

    this.show = function() { 
     console.log(this.name+' triggered'); 
    } 
} 

y = new subcounter(2,'y',function(){alert('finished')}); 
x = new subcounter(2,'x',y, "show"); 
+0

這工作。然而它不靈活。正如你所看到的,我希望能夠傳遞任何函數來觸發。 –

+0

@ guillermo-phillips我已經更新了我的答案。現在您可以傳遞對象和方法名稱來調用。 – blessenm