Object.prototype.constructor
>Object 实例的 constructor 数据属性返回一个引用,指向创建该实例对象的构造函数。注意,此属性的值是对函数本身的引用,而不是一个包含函数名称的字符串。
备注:这是 JavaScript 对象的一个属性。关于类的 constructor 方法,请参见其参考页面。
值
对创建该实例对象的构造函数的引用。
Object.prototype.constructor 的属性特性 | |
|---|---|
| 可写 | 是 |
| 可枚举 | 否 |
| 可配置 | 是 |
备注:这个属性默认会在每个构造函数的 prototype 属性上创建,并由该构造函数创建的所有对象继承。
描述
除了 null 原型对象之外,任何对象都会在其 [[Prototype]] 上有一个 constructor 属性。使用字面量创建的对象也会有一个指向该对象构造函数类型的 constructor 属性,例如,数组字面量创建的 Array 对象和对象字面量创建的普通对象。
js
const o1 = {};
o1.constructor === Object; // true
const o2 = new Object();
o2.constructor === Object; // true
const a1 = [];
a1.constructor === Array; // true
const a2 = new Array();
a2.constructor === Array; // true
const n = 3;
n.constructor === Number; // true
请注意,constructor 属性通常来自构造函数的 prototype 属性。如果你有一个更长的原型链,通常可以假定链中的每个对象都有一个 constructor 属性。
js
const o = new TypeError(); // 继承关系:TypeError -> Error -> Object
const proto = Object.getPrototypeOf;
proto(o).constructor === TypeError; // true
proto(proto(o)).constructor === Error; // true
proto(proto(proto(o))).constructor === Object; // true
示例
>打印对象的构造函数
下面这个示例创建一个构造函数(Tree),以及该类型的对象(theTree)。然后打印了 theTree 对象的 constructor 属性。
js
function Tree(name) {
this.name = name;
}
const theTree = new Tree("Redwood");
console.log(`theTree.constructor 是 ${theTree.constructor}`);
这个示例会打印以下输出:
theTree.constructor 是 function Tree(name) {
this.name = name;
}
为对象的 constructor 属性赋值
可以为非基本类型对象的 constructor 属性赋值。
js
const arr = [];
arr.constructor = String;
arr.constructor === String; // true
arr instanceof String; // false
arr instanceof Array; // true
const foo = new Foo();
foo.constructor = "bar";
foo.constructor === "bar"; // true
// 等等…
这不会覆盖旧的 constructor 属性——它实际上存在于实例的 [[Prototype]] 中,而不是作为其自有属性。
js
const arr = [];
Object.hasOwn(arr, "constructor"); // false
Object.hasOwn(Object.getPrototypeOf(arr), "constructor"); // true
arr.constructor = String;
Object.hasOwn(arr, "constructor"); // true——实例属性会覆盖原型链上的同名属性
但是,即使对 Object.getPrototypeOf(a).constructor 重新赋值,它也不会改变对象的其他行为。例如,instanceof 的行为由 Symbol.hasInstance 控制,而不是由 constructor 控制:
js