Javascript &引用;“未定义”;在累加器的末尾。value()

Javascript &引用;“未定义”;在累加器的末尾。value(),javascript,function,constructor,Javascript,Function,Constructor,我在构造函数函数方法中遇到了值错位的问题。结果。我不明白为什么我会得到函数结束时的结果-未定义 请告诉我,函数中忘记包含什么:( 如果.value应为整数,则不要将其定义为函数:-) 我认为你应该放下.value(),.startingValue和.a,到处使用.value。将总和直接放入read方法中。简化为: function Accumulator(startingValue) { this.value = startingValue; this.read = funct

我在
构造函数
函数
方法
中遇到了值错位的问题。结果
。我不明白为什么我会得到
函数结束时的结果
-
未定义

请告诉我,
函数中忘记包含什么:(


如果
.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;
    }
}
有两个问题

this.value = function() {
    this.value += this.a; //this.value is a function
};

成功

功能累加器(启动值){
this.startingValue=startingValue;
this.read=函数(){
this.a=(this.a | | | this.startingValue)+提示符('您的数字:','');//初始化并添加提示值
};
this.value=函数(){

返回此值。a;//只需返回值 }; this.result=函数(){ 返回this.a+this.startingValue;//this.a代替this.value } } var累加器=新累加器(1); 累加器read(); 累加器read();
console.log(acculator.value());//调用方法
累加器。value
应该是整数还是函数?@bergi应该是整数,但不要将其定义为函数:-)我认为您应该删除
.value()
.startingValue
.a
,并在任何地方使用
.value
。将求和直接放入
read
方法。返回值
read
除非调用
value
,否则不会执行任何操作,并且值未定义,因此无法
未定义+1212
哦。。。现在我知道我错过了什么。谢谢你,老兄!干杯
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