0

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 ?

1
  • What are you trying to do? You create two instances of person, but that is all. You never call greet() on any of them? Commented Jul 2, 2015 at 3:07

1 Answer 1

3

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.