The constructor property always points to the constructor that created the current object. For example, the following example:
// Equivalent In var foo = new Array(1, 56, 34, 12);
var arr = [1, 56, 34, 12];
console.log(arr.constructor === Array); // true
// Equivalent to var foo = new Function();
var Foo = function() { };
console.log(Foo.constructor === Function); // true
// Instantiate an obj object by the constructor
var obj = new Foo();
console.log(obj.constructor === Foo); // true
// Replace the above two paragraphs Putting the code together, we get the following conclusion
console.log(obj.constructor.constructor === Function); // true
But when the constructor encounters prototype, something interesting happens It just happened.
We know that each function has a default attribute prototype, and the constructor of this prototype points to this function by default. As shown in the following example:
function Person(name) {
this.name = name;
};
Person.prototype.getName = function() {
return this.name;
};
var p = new Person("ZhangSan ");
console.log(p.constructor === Person); // true
console.log(Person.prototype.constructor === Person); // true
// will be above The two lines of code are combined to get the following result
console.log(p.constructor.prototype.constructor === Person); // true
When we redefine the prototype of the function ( Note: The difference from the above example, here is not to modify but to overwrite), the behavior of the constructor attribute is a bit strange, as shown in the following example:
function Person(name) {
this.name = name;
};
Person.prototype = {
getName: function () {
return this.name;
}
};
var p = new Person("ZhangSan");
console.log(p.constructor === Person); // false
console.log(Person.prototype.constructor === Person); // false
console.log(p.constructor.prototype.constructor === Person); // false
Why?
It turns out that when overwriting Person.prototype, it is equivalent to the following code operation:
Person.prototype = new Object({
getName: function() {
return this.name;
}
});
The constructor attribute always points to the constructor that creates itself, so at this time Person.prototype.constructor === Object, that is:
function Person(name) {
this.name = name;
};
Person.prototype = {
getName: function() {
return this.name;
}
};
var p = new Person("ZhangSan");
console.log(p.constructor === Object) ; // true
console.log(Person.prototype.constructor === Object); // true
console.log(p.constructor.prototype.constructor === Object); // true
How to fix this problem? The method is also very simple, just re-overwrite Person.prototype.constructor:
function Person(name) {
this.name = name;
};
Person.prototype = new Object({
getName: function() {
return this.name ;
}
});
Person.prototype.constructor = Person;
var p = new Person("ZhangSan");
console.log(p.constructor === Person ); // true
console.log(Person.prototype.constructor === Person); // true
console.log(p.constructor.prototype.constructor === Person); // true