Ying Joy
Ying Joy

Reputation: 21

JavaScript Object for..in loop

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

Answers (4)

annz
annz

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

Agnibha
Agnibha

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

morsecodist
morsecodist

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

CertainPerformance
CertainPerformance

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

Related Questions