Question:
Why does the greet function not return the expected value?
Code:
function Person(name){
this.name = name;
}
Person.prototype.greet = function(otherName){
return "Hi" + otherName + ", my name is " + name;
}
How do I answer this? I create a new person then what do I do?
var John = new Person("John");
Wrong access method. the variable name
isn't defined, only this.name
is defined. So it's looking for a variable in the function scope called name
instead of a property of the object called name
.
To access an object's property from within the object we use the this
keyword. Thus we'll need to use this.name
to access the name
property in the implementation below.
Person.prototype.greet = function(otherName){
return "Hi" + otherName + ", my name is " + this.name;
}
In your code:
> function Person(name) {
> this.name = name;
> }
When called as a constructor, the above will create a named property of an instance called name and assign it the value of the name parameter.
> Person.prototype.greet = function(otherName){
> return "Hi" + otherName + ", my name is " + name;
> }
Here the identifier name is used as a variable, but the identifier you are looking for is a named property of the instance, so you need to access it at as such. Typically, this function will be called as a method of the instance so this within the function will be a reference to the instance. So you want:
return "Hi" + otherName + ", my name is " + this.name;
So now when you can do (note that variables starting with a capital letter are, by convention, reserved for construtors):
> var john = new Person("John");
and then:
john.greet('Fred');
because greet is called as a method of john, it will return:
Hi Fred, my name is John
Alternatively, since this is an issue of scope inheritance (second function not having access to the variable "name"), we can rephrase the code to look like this to include it all under the Person function:
function Person(name){
this.name = name;
this.greet = function(otherName){
return "Hi" + otherName + ", my name is " + name;
}
}
Works as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With