accumulator.value()末尾的"Undefined"

Svi*_*lev 3 javascript constructor function

我遇到了价值错位的问题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
Run Code Online (Sandbox Code Playgroud)

Ber*_*rgi 5

如果.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
Run Code Online (Sandbox Code Playgroud)

您可能还想在原型上定义方法:

function Accumulator(startingValue) {
    this.value = startingValue;
}
Accumulator.prototype.read = function() {
    this.value += +prompt('Your digit: ', '');
};
Accumulator.prototype.result = function() {
    return this.value;
};
Run Code Online (Sandbox Code Playgroud)

甚至使用现代class语法,如@ArtificialBug建议:

class Accumulator {
    constructor(startingValue) {
        this.value = startingValue;
    }
    read() {
        this.value += parseInt(prompt('Your digit: ', ''), 10);
    }
    result() {
        return this.value;
    }
}
Run Code Online (Sandbox Code Playgroud)