An in depth analysis of constructor in JavaScript

  • 2021-02-17 06:10:27
  • OfStack

Definitions and Usage

The constructor property returns a reference to the array function that created this object.

grammar

object.constructor

constructor, constructor, we're all familiar with this name, constructor always points to the constructor that created the current object.

One important thing to note here is that each function has an prototype attribute. The constructor of the prototype refers to the function. When we modify the prototype of the function, we have an accident. Such 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 so:


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 has 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 created the current object, it is not difficult to understand that the above code, p.constructor, outputs Object.

What if you modify constructor and want it to point to Person? Person.prototype.constructor: Person.prototype.constructor: Person.prototype.constructor: Person.prototype.constructor


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

The above is this site to introduce JavaScript in constructor, I hope to help you!


Related articles: