On constructor in javascript

  • 2021-06-28 10:04:48
  • OfStack

constructor, the constructor, is familiar with this name, and constructor always points to the constructor that creates the current object.

One thing to note here is that each function has an prototype attribute, which constructor of prototype points to. When we modify prototype of this function, something unexpected happens.as


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

Person.prototype.getAge = function(){
  return this.age;
}
Person.prototype.getName = function(){
  return this.name;
}

var p = new Person("Nicholas",18);
console.log(p.constructor); //Person(name, age)
console.log(p.getAge()); //18
console.log(p.getName()); //Nicholas

But if this is the case:


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

Person.prototype = {
  getName:function(){
    return this.name;
  },
  getAge:function(){
    return this.age;
  }
}

var p = new Person("Nicholas",18);
console.log(p.constructor); //Object()
console.log(p.getAge()); //18
console.log(p.getName()); //Nicholas

As a result, constructor changed.

The reason is that prototype itself is an object, and the code above is equivalent to


Person.prototype = new Object({
  getName:function(){
    return this.name;
  },
  getAge:function(){
    return this.age;
  }
});

Because constructor always points to the constructor that creates the current object, it is not difficult to understand that the code p.constructor above outputs Object.

What should constructor do if it wants to point to Person after modifying prototype?Simple, just assign a value to Person.prototype.constructor:


Person.prototype = {
  constructor:Person,
  getName:function(){
    return this.name;
  },
  getAge:function(){
    return this.age;
  }
}

Related articles: