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.
I have a JSFiddle fiddle for this: http://jsfiddle.net/dennisboys/LZeQr/1/
Here’s the problem:
This will loop through all properties of
this. Let’s see those properties:You’ve got 4 properties which is what you see getting printed to the console.
You should use the
hasOwnPropertymethod:And here’s a live demo.