Prototypes and function (codewars)


#1

Hi,

I am not sure what I am doing wrong.

My code Error returns: TestError: Expected: Hi Kate, my name is Joe, instead got: Hi undefined, my name is Joe.

Thanks in advance.

function Person(name, otherName) {
this.name = name;
this.otherName = otherName;
}

Person.prototype.greet = function(){
return "Hi " + this.otherName + ", my name is " + this.name;
}

//Creating new person
var joe = new Person("Joe", "Kate");

//Call the function
joe.greet();


#2

Is this an exercise in codecademy.com? A link might be helpful to exact exercise.

That said, your code will print with a single quotes because of this:

See screenshot.

I am suggesting you do:

console.log ( "Hi " + this.otherName + ", my name is " + this.name);

instead.

Let me know if this resolves.


#3

This exercise is from codewars. I also tried the console log and it returns the entire log as undefined.

Here is the original code and its instructions.

Correct this code, so that the greet function returns the expected value.

function Person(name){
this.name = name;
}

Person.prototype.greet = function(otherName){
return "Hi " + otherName + ", my name is " + name;
}


#4

wait a sec...
in

function Person(name){

you would declare as a variable like

var person = function(name) {

or am i missing some part here?


#5

Actually 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;
}

#6

That's why I thought that giving the function two parameters would fix the issue, but it did not. Perhaps there is a bug. unless they are looking to solve it in a very specific way.

but the two ways that you have defined the function are equally the same if I am not mistaken. Right?
function Person(name){
&
var person = function(name) {


#7

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.


#8

It was a question of scope @drrobotnic. Thanks a bunch.
I created the new Person after that and called the function passing joe.
and Gold. :grin:


#9

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.