In-depth analysis of constructor in JavaScript
Definition and usage
The constructor attribute returns a reference to the array function that creates this object.
Syntax
Object. constructor
Constructor, constructor. We are familiar with this name. constructor always points to the constructor that creates the current object.
Note that each function has a prototype attribute. This prototype constructor points to this function. When we modify the prototype of this function, an exception occurs. For example
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()); //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()); //18console.log(p.getName()); //Nicholas
The constructor is changed.
The reason is that prototype itself is also an object, and the above Code is equivalent
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 above Code p. constructor outputs the Object.
What should I do if the constructor After prototype modification still wants to point it to Person? Simple: assign a 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, which I want to help you!