我遇到了constructor function method this.result中的值错位问题。我不明白为什么我会得到function -undefined结束的结果.
请告诉我,在function中忘记了什么:
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发布于 2017-12-21 12:31:40
如果.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您还可能希望在原型上定义方法:
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;
}
}发布于 2017-12-21 12:32:57
有两个问题
this.value = function() {
this.value += this.a; //this.value is a function
};和
console.log( accumulator.value ); // accumulator value is a function which needs to be invoked搞定
function Accumulator(startingValue) {
this.startingValue = startingValue;
this.read = function() {
this.a = (this.a || this.startingValue ) + +prompt('Your digit: ', '');//initialize and add the prompted value
};
this.value = function() {
return this.a; //simply return the value
};
this.result = function() {
return this.a + this.startingValue; //this.a instead of this.value
}
}
var accumulator = new Accumulator(1);
accumulator.read();
accumulator.read();
console.log( accumulator.value() ); // invoke the method
https://stackoverflow.com/questions/47924965
复制相似问题