Home >Web Front-end >JS Tutorial >A brief discussion on constructor_basic knowledge in javascript
Now I will bring you a brief discussion of the constructor in javascript. Let me share it with you now and give it as a reference for everyone.
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 attribute, and the constructor of this prototype points to this function. This happens when we modify the prototype of this function. 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 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, the constructor has changed.
The reason is that prototype itself is also an object. 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 the above code p.constructor The output is Object.
What should I do if I still want the constructor to point to Person after modifying the prototype? It's simple, just assign a value to Person.prototype.constructor directly:
Person.prototype = { constructor:Person, getName:function(){ return this.name; }, getAge:function(){ return this.age; } }
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
Using JavascriptSimple implementation of cropping pictures and storing them
About JavaScript Array (array ) How to use the object
UseJavascriptSimple implementation of cropping pictures and storing them
The above is the detailed content of A brief discussion on constructor_basic knowledge in javascript. For more information, please follow other related articles on the PHP Chinese website!