Reputation: 8589
I am trying to resolve a problem but I need to understand prototype.
I was reading and I thought I got it, but I am still having some complications
function Person(name){
this.name = name;
}
Person.prototype.greet = function(otherName){
return "Hi " + otherName + ", my name is " + name;
}
var kate = new Person('Kate'); //name
var jose = new Person('Jose'); //otherName ???
so, is my mistake when I need to call the function ? or where is it ?
Upvotes: 0
Views: 39
Reputation: 388316
The name
is a property of the object instance, so you need to use this.name
in the greet
method.
From what I understand, you need to display Hi Jose, my name is Kate
like a greeting. In that case you need to pass the other person
to the greet
method then you can access that persons name using object.name
function Person(name) {
this.name = name;
}
Person.prototype.greet = function(other) {
return "Hi " + other.name + ", my name is " + this.name;
}
var kate = new Person('Kate');
var jose = new Person('Jose');
snippet.log(kate.greet(jose));
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Upvotes: 3