3

这是我的代码,我希望它打印出一个数字,而是打印出一个数字加上我的所有代码。

function Employee(salaryJan, salaryFeb, salaryMar){
    this.salaryJan = salaryJan;
    this.salaryFeb = salaryFeb;
    this.salaryMar = salaryMar;
}

var dennis = new Employee(6575, 7631, 8000);

Employee.prototype.sumAll = function(){
    var sum = 0;
    for (salary in this){
        sum += this[salary];
    }
    console.log(sum);
};

dennis.sumAll();

目前我的代码打印出来:

22206function (){
    var sum = 0;
    for (salary in this){
        sum += this[salary];
    }
    console.log(sum);
}

我只是想要22206,我不知道为什么它还会打印出一些代码。

我有一个 JSFiddle 小提琴:http: //jsfiddle.net/dennisboys/LZeQr/1/

4

1 回答 1

4

这是问题所在:

for (salary in this)

这将遍历this. 让我们看看这些属性:

this.salaryJan
this.salaryFeb
this.salaryMar
Employee.prototype.sumAll

您有 4 个属性,这是您看到的打印到控制台的内容。

您应该使用以下hasOwnProperty方法:

for (prop in this) {
    if (this.hasOwnProperty(prop)) 
        sum += this[prop];
    }
}

这是一个现场演示

于 2013-01-18T06:46:13.267 回答