SoFunction
Updated on 2025-04-08

JavaScript classes and inheritance constructor properties

The constructor property always points to the constructor that created the current object. For example, the following example: For example, the following example:
Copy the codeThe code is as follows:

// Equivalent to var foo = new Array(1, 56, 34, 12);
var arr = [1, 56, 34, 12];
( === Array); // true
// is equivalent to var foo = new Function();
var Foo = function() { };
( === Function); // true
// Instantiate an obj object by the constructor
var obj = new Foo();
( === Foo); // true
// Combine the above two codes and get the following conclusion
( === Function); // true

But when the constructor encounters prototype, something interesting happens.
We know that each function has a default property prototype, and the constructor of this prototype points to this function by default. As shown in the following example:
Copy the codeThe code is as follows:

function Person(name) {
= name;
};
= function() {
return ;
};
var p = new Person("ZhangSan");
( === Person); // true
( === Person); // true
// Merge the previous two lines of code to get the following results
( === Person); // true

When we redefine the prototype of the function (note: the difference between the above example, it is not modified but overridden here), the behavior of the constructor attribute is a bit strange, as shown in the following example:
Copy the codeThe code is as follows:

function Person(name) {
= name;
};
= {
getName: function() {
return ;
}
};
var p = new Person("ZhangSan");
( === Person); // false
( === Person); // false
( === Person); // false

Why?
It turns out that when it is covered, it is equivalent to performing the following code operation:
Copy the codeThe code is as follows:

= new Object({
getName: function() {
return ;
}
});

The constructor attribute always points to the constructor that creates its own, so at this time === Object, that is:
Copy the codeThe code is as follows:

function Person(name) {
= name;
};
= {
getName: function() {
return ;
}
};
var p = new Person("ZhangSan");
( === Object); // true
( === Object); // true
( === Object); // true

How to fix this problem? The method is also very simple, just re-cover:
Copy the codeThe code is as follows:

function Person(name) {
= name;
};
= new Object({
getName: function() {
return ;
}
});
= Person;
var p = new Person("ZhangSan");
( === Person); // true
( === Person); // true
( === Person); // true