javascript - accumulator.value() 末尾的 "Undefined"

标签 javascript function constructor

我在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/

相关文章:

c++ - 当使用 bool 值构造字符串对象时,发生了什么类型转换?

javascript - Backbone.js 和 XSS/HTML 转义

javascript - 如何在 Angularjs 中使用 Dropzone 显示已存储在服务器上的文件

javascript - JQuery 函数在输入键时不触发

javascript - 在 Javascript 中将函数作为参数传递

postgresql - 是否可以在 postgresql 中使用 for 循环(功能)

javascript - 在构造函数 javascript 中将属性设置为函数

c++ - 对于类构造函数,通过括号或等号赋值有什么区别?

javascript - 获取数组中的对象,该对象具有一个属性,该属性是一个包含匹配值的数组

javascript - 如何使用 JavaScript 更改链接的 URL?