Reputation: 49
This is a kata for code wars, and I can't seem to figure it out. I have never worked with JavaScript before.
I know the answer is probably simple, but I just can't seem to figure out what they are looking for even after many hours of searching. I know that name
in the greet
function is not defined, but when I define it, it says it's not the value it's looking for.
function Person(name){
this.name = name;
}
Person.prototype.greet = function(otherName){
return "Hi " + otherName + ", my name is " + name;
}
Please help and an explanation would be greatly appreciated.
Upvotes: 1
Views: 9444
Reputation: 3833
I don't get your question but i will try to explain how it works:
// define a function (or class) called 'Person'
function Person(name){
// add data members 'name' to 'this' pointer which points to current context
this.name = name;
}
// define a method in 'Person' class
Person.prototype.greet = function(otherName){
//'othername' is an argument which you passed while calling 'greet' method
//'name' is an data memeber which you declared while creating 'Person' class
// will return value when you call this method
return "Hi " + otherName + ", my name is " + this.name;
}
// create a class object
var person = new Person('Mohit');
// call its 'greet' method
// will show an alert 'Hi Bekk, my name is Mohit'
alert(person.greet('Bekk'));
JSFiddle Link: http://jsfiddle.net/QqnL5/
Upvotes: 1
Reputation: 19528
Tyagi gave you an explanation of how to call it but did not show what the actual problem with the code is:
Here's my (very similar) example:
function Person(name) {
this.name = name;
}
Person.prototype.greet = function (otherName) {
return "Hi " + otherName + ", my name is " + this.name;
}
var john = new Person("John");
$("#result").text(john.greet("Mike"));
and if you click through to this JSFiddle then you can see it actually working. The difference between the two is simply the change of "name" to "this.name" in the greet() function. You're attaching a new function to every Person object but it doesn't automatically look for the name variable on the object within that function the way it's defined.
Upvotes: 1
Reputation: 2375
Don't really understand what you are looking for but hope this will shed some light : (try on your console)
function Person(name){
this.name = name;
}
Person.prototype.greet = function(otherName){
return "Hi " + otherName + ", my name is " + this.name;
}
var p = new Person('jack');
p.greet('sparrow');
Upvotes: 3