Home > Back-end >  Javascript prototype - Variable remains undefined
Javascript prototype - Variable remains undefined

Time:01-21

I have below code snipet -

function Person(first, last, age, eyecolor) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eyecolor;
}

var person=new Person("MyName","MySirname",14,"Black")
Person.prototype.FullName=this.firstName " " this.lastName
console.log(person.FullName)

Here in this example code is pronting undefined undefined; whereas I expect - MyName MySirname

CodePudding user response:

The reason for this is that the line Person.prototype.FullName = this.firstName " " this.lastName is executed when the Person constructor is called and at that time, the value of this is the global object. Therefore, the value of this.firstName and this.lastName are undefined and hence the result is undefined undefined.

The correct way to set the FullName property would be to use the parameters passed to the constructor, like this:

Person.prototype.FullName = function() {
  return this.firstName   " "   this.lastName;
};

Then you can call the FullName method on the person object like this:

console.log(person.FullName()); // MyName MySirname
  • Related