function distance(r,t){
        this.rate = r,
        this.time = t,
        this.calculate = function() {return rate * time ;};
        return this;
}

var trip1 = distance(2,4);
var trip2 = distance(5,7);
var trip3 = distance(3,10);
document.write("<br>trip1: " + trip1.calculate());
document.write("<br>trip2: " + trip2.calculate());
document.write("<br>trip3: " + trip3.calculate());


输出

trip1: 30
trip2: 30
trip3: 30


输出不应该是

trip1: 8
trip2: 35
trip3: 30

最佳答案

每个新距离应该是一个新对象。另外,在内部计算中,您必须通过“ this”键引用当前实例

function distance(r,t){
        this.rate = r,
        this.time = t,
        this.calculate = function() {return this.rate * this.time ;};
        return this;
}

var trip1 = new distance(2,4);
var trip2 = new distance(5,7);
var trip3 = new distance(3,10);
document.write("<br>trip1: " + trip1.calculate());
document.write("<br>trip2: " + trip2.calculate());
document.write("<br>trip3: " + trip3.calculate());


编辑上面没有NEW关键字的示例:

function distance(r,t){
        if ( !(this instanceof distance) ) //checking if I'm using 'new' or not
            return new distance(r, t);
        this.rate = r,
        this.time = t,
        this.calculate = function() {return this.rate * this.time ;};
        return this;
}

var trip1 = distance(2,4);
var trip2 = distance(5,7);
var trip3 = distance(3,10);
document.write("<br>trip1: " + trip1.calculate());
document.write("<br>trip2: " + trip2.calculate());
document.write("<br>trip3: " + trip3.calculate());

关于javascript - JavaScript和这个,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4689396/

10-10 19:20