我在constructor
function
method
this.result
中遇到了值错位的问题。我不明白为什么我会得到 function
结束的结果 - undefined
...
请告诉我,函数
中忘记包含什么:(
function Accumulator(startingValue) {
this.startingValue = startingValue;
this.read = function() {
this.a = +prompt('Your digit: ', '');
};
this.value = function() {
this.value += this.a;
};
this.result = function() {
return this.value + this.startingValue;
}
}
var accumulator = new Accumulator(1); // starting value 1
accumulator.read(); // sum prompt with current value
accumulator.read(); // sum current prompt with previous prompt and current value
console.log( accumulator.result() ); // display sum result
最佳答案
如果 .value
应该是一个整数,不要将它定义为一个函数:-)
我认为您应该删除 .value()
、.startingValue
和 .a
并只使用 .value
无处不在。将求和直接放入read
方法。简化为:
function Accumulator(startingValue) {
this.value = startingValue;
this.read = function() {
// the temporary variable might be unnecessary but I left it in for verbosity
const a = +prompt('Your digit: ', '');
this.value += a;
};
this.result = function() {
return this.value;
};
}
var accumulator = new Accumulator(1); // starting value 1
accumulator.read(); // add prompt to current value
accumulator.read(); // add another prompt to current value
console.log( accumulator.result() ); // display sum by calling result() method
您可能还想在原型(prototype)上定义方法:
function Accumulator(startingValue) {
this.value = startingValue;
}
Accumulator.prototype.read = function() {
this.value += +prompt('Your digit: ', '');
};
Accumulator.prototype.result = function() {
return this.value;
};
甚至使用现代的 class
语法,正如@ArtificialBug 所建议的那样:
class Accumulator {
constructor(startingValue) {
this.value = startingValue;
}
read() {
this.value += parseInt(prompt('Your digit: ', ''), 10);
}
result() {
return this.value;
}
}
关于javascript - accumulator.value() 末尾的 "Undefined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47924965/