accumulator.value()末尾的“Undefined”

问题描述 投票:3回答:2

我遇到了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
javascript function constructor
2个回答
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

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

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;
    }
}

1
投票

有两个问题

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
© www.soinside.com 2019 - 2024. All rights reserved.