简体   繁体   English

为什么我的代码没有产生预期的结果? 它打印的比我想要的多

[英]Why does my code not produce the expected result? It prints more than what I want

Here is my code and I expect it prints out a number, instead, it prints out a number plus all my codes.这是我的代码,我希望它打印出一个数字,相反,它打印出一个数字加上我的所有代码。

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();

Currently my codes prints out:目前我的代码打印出来:

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

I just want 22206 , and I have no idea why it also prints out some code.我只想要22206 ,我不知道为什么它还会打印出一些代码。

I have a JSFiddle fiddle for this: http://jsfiddle.net/dennisboys/LZeQr/1/我有一个 JSFiddle 小提琴: http : //jsfiddle.net/dennisboys/LZeQr/1/

Here's the problem:这是问题所在:

for (salary in this)

This will loop through all properties of this .这将遍历this所有属性。 Let's see those properties:让我们看看这些属性:

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

You've got 4 properties which is what you see getting printed to the console.您有 4 个属性,这就是您看到的打印到控制台的内容。

You should use the hasOwnProperty method:您应该使用hasOwnProperty方法:

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

And here's a live demo .这是一个现场演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM