Home  >  Article  >  Web Front-end  >  An in-depth analysis of the constructor in JavaScript

An in-depth analysis of the constructor in JavaScript

PHPz
PHPzOriginal
2016-05-16 15:04:551798browse

The constructor property returns a reference to the array function that created this object. This article will introduce you to the constructor in JavaScript. Friends who need it can refer to it.

Definition and Usage

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

Syntax

object.constructor

constructor, constructor, we are all familiar with this name, constructor is always Pointer to the constructor that created 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. At this time, when we modified the prototype of this function, an accident occurred. 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. , then it is not difficult to understand that the output of p.constructor in the above code is Object.

What should I do if the constructor after modifying the prototype still wants it to point to Person? Simple, just assign value to Person.prototype.constructor directly:

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

The above is the constructor in JavaScript introduced by the editor. For more related tutorials, please visit JavaScript video tutorial!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn