Definition and usage
The constructor property returns a reference to the array function that created this object.
grammar
object.constructor
constructor, constructor, we are all familiar with this name. constructor always points to the constructor that creates the current object.
One thing to note here is that each function has a prototype property, and the constructor of this prototype points to this function. At this time, when we modify the prototype of this function, an accident happened. like
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()); //18console.log(p.getName()); //NicholasBut 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()); //18console.log(p.getName()); //NicholasAs a result, the constructor changed.
The reason is that prototype itself is also an object, and the above code is equivalent to
Person.prototype = new Object({getName:function(){return this.name;},getAge:function(){return this.age;}});Because the constructor always points to the constructor that creates the current object, it is not difficult to understand that the above code p.constructor outputs an Object.
What should I do if the constructor after modifying the prototype and still wants it to point to Person? Simple, just assign value to Person.prototype.constructor:
Person.prototype = {constructor:Person,getName:function(){return this.name;},getAge:function(){return this.age;}}The above is the constructor in JavaScript introduced to you by the editor. I hope it will be helpful to everyone!