user3014361
user3014361

Reputation: 1

Java script:About function within an object

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

Answers (4)

CookieCoder
CookieCoder

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

Ankit Tyagi
Ankit Tyagi

Reputation: 2375

You can also use :

this.changeName = function(name)
{
this.lastname=name;
}

Upvotes: 0

Korvo
Korvo

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

tymeJV
tymeJV

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

Related Questions