2015-04-06 54 views
-2

我需要創建一個構造函數,以提醒increament價值,如何做到這一點?增量的JavaScript

這是我

var increment = new Increment(); 

alert(increment); /* 1 */ 
alert(increment); /* 2 */ 
alert(increment + increment); /* 7 */ 
+2

但是........爲什麼! – adeneo 2015-04-06 11:22:00

+0

另外,不能做!在你的代碼'increment'只是一個參考,它不能增加whitout叫什麼 – adeneo 2015-04-06 11:22:55

回答

2

輕鬆!

function Increment(){ 
this.i = 0; 
} 

Increment.prototype.toString = function(){ 
this.i++; 
return this.i; 
} 

var increment = new Increment(); 
+0

謝謝你,這是我需要什麼 – Ap333 2015-04-06 11:50:35

+1

我不知道爲什麼這是有用的或必要的。 '的console.log(增量)'不會做任何有意義的事,也不會使用'increment'在任何環境中,是不是要被轉換成字符串。 – 2015-04-06 12:10:57

+0

好吧,如果你想檢查多少次'increment'被訪問......這可能是怪異的情況下非常有用。 – mkaminsky 2015-04-06 18:57:21