Reputation: 21
This is my code:
function person(name, age) {
this.name = name;
this.age = age;
this.changeName = changeName;
function changeName(name) {
this.name = name;
}
}
my = new person("Ying", 21);
for (i in my) {
document.write(my[i] + " ");
}
Result:
Ying 21 function changeName(name) { this.name = name; }
why does it output the changeName() method?
Upvotes: 0
Views: 66
Reputation: 319
function person(name, age) {
this.name = name;
this.age = age;
this.changeName = changeName;
function changeName(name) {
this.name = name;
}
}
my = new person("Ying", 21);
for (i in my) {
if (typeof my[i] !== 'function') document.write(my[i] + " ");
}
Upvotes: 0
Reputation: 693
When you create a constructor function every thing that you define within the function gets attached to the constructed object because of javascript being function scoped. So your function is associated with the this. Hence the problem that you face.
Upvotes: 0
Reputation: 947
In javascript methods aren't special. They are members of the object like any other. If you want to ignore them you can do this:
my = new person("Ying", 21);
for (i in my) {
if (typeof my[i] !== 'function') document.write(my[i] + " ");
}
This skips over keys whose members are functions.
Upvotes: 0
Reputation: 371233
When it comes to the changeName property, you're using the + operator on a function, so it gets implicitly converted to a string. You might want something like this instead:
if (typeof my[i] !== 'function') document.write(my[i] + " ");
Upvotes: 1