0

not sure whats the this used for: "this.changeName = changeName;" if i delete this line the code doesn't work fine. But this line seems do nothing.

<!DOCTYPE html>
<html>
<body>
<script>
function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
this.changeName = changeName;
function changeName(name)
{
this.lastname=name;
}
}
myMother=new person("Sally","Rally",48,"green");
myMother.changeName("Doe");
document.write(myMother.changeName);
</script>

</body>
</html>
  • 1
    I think your confusion is a result of `variable hoisting`. You should see this thread for discussion on the topic: http://stackoverflow.com/questions/3725546/variable-hoisting – megawac Nov 20 '13 at 18:17
  • Hi! My answer solve your problem? If so check as "correct", if not tell me what is missing. – Protomen Apr 12 '15 at 15:22

4 Answers4

1

this.changename assigns the private changeName function to the Objects instance. So, when you create a new Object of type person, person has the method changename because of this.changename which assigns changeName as the function to execute.

tymeJV
  • 103,943
  • 14
  • 161
  • 157
0

Try:

function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
this.changeName = function(name) {
this.lastname=name;
}
}
Protomen
  • 9,471
  • 9
  • 57
  • 124
0

You can also use :

this.changeName = function(name)
{
this.lastname=name;
}
Ankit Tyagi
  • 2,381
  • 10
  • 19
0

The function changeName is a method on the object person, which you set when you say this.changeName = changeName; this meaning the person object.

You're not using that function until you call it here myMother.changeName("Doe");

In which you are changing the last name to "Doe" So myMother.lastname = "Doe"

I'm kind of repeating what the others are saying, but hoping that it is more clear.

CookieCoder
  • 351
  • 2
  • 6