0

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?

1
  • 3
    Why shouldn't it? It's a member of your person object. Commented Mar 20, 2018 at 3:48

4 Answers 4

1

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] + " ");
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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.

Comments

0

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] + " ");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.