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 brief discussion on constructor in JavaScript is all the content I share with you. I hope it can give you a reference and I hope you can support Wulin.com more.