建立新的累加器
重要性:5
建立建構函式函式 Accumulator(startingValue)
。
它所建立的物件應該
- 將「目前值」儲存在屬性
value
中。起始值設定為建構函式startingValue
的引數。 read()
方法應該使用prompt
讀取新的數字並將其加入value
。
換句話說,value
屬性是所有使用者輸入值與初始值 startingValue
的總和。
以下是程式碼的示範
let accumulator = new Accumulator(1); // initial value 1
accumulator.read(); // adds the user-entered value
accumulator.read(); // adds the user-entered value
alert(accumulator.value); // shows the sum of these values
function Accumulator(startingValue) {
this.value = startingValue;
this.read = function() {
this.value += +prompt('How much to add?', 0);
};
}
let accumulator = new Accumulator(1);
accumulator.read();
accumulator.read();
alert(accumulator.value);