Reputation: 1
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>
Upvotes: 0
Views: 60
Reputation: 361
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.
Upvotes: 0
Reputation: 2375
You can also use :
this.changeName = function(name)
{
this.lastname=name;
}
Upvotes: 0
Reputation: 9714
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;
}
}
Upvotes: 0
Reputation: 104775
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.
Upvotes: 1