When是实际使用的对象的“.constructor”属性

When is the `.constructor` property of an object actually used

本文关键字:对象 属性 constructor When      更新时间:2023-09-26

我一直在使用这样的代码来继承另一个对象:

// define base object constructor
function SuperType(){
    // constructor code
}
// define base object methods on the prototype
SuperType.prototype.foo = function() {};
// ---------------------------------------------------------------------------
// define object that wants to inherit from the SuperType object
function SubType() {
    // call base object constructor with all arguments that might have been passed
    SuperType.apply(this, arguments); 
    // other constructor code
}
// set prototype for this object to point to base object
// so we inherit any items set on the base object's prototype
SubType.prototype = new SuperType();
// reset constructor to point to this object not to SuperType
SubType.prototype.constructor = SubType;
// define any methods of this object by adding them to the prototype
SubType.prototype.myMethod = function() {};

我的问题是为什么你必须设置SubType.constructor = SubType.constructor属性实际何时使用?如果您创建一个SubType对象,如下所示:

var s = new SubType();

这将调用SubType()构造函数,而不管SubType.prototype.constructor实际设置为什么,所以我试图了解.constructor属性何时实际使用?


正如您在这个jsFiddle演示中看到的,对.constructor的赋值被注释掉了,正确的构造函数仍然被调用。因此,在new运算符的正常构造中似乎没有使用.constructor属性。我想知道它什么时候用?

根据ECMAScript语言规范,

Object.prototype.constructor的初始值是标准的内置Object构造函数。

换句话说,它只是一个指向Object实际的本机构造函数的指针——通过new Object()调用的构造函数。因此,您可以覆盖它,而无需更改new Object()的工作方式。

那么它为什么存在呢?因为构造函数实际上是JavaScript中的类,所以它允许您在不需要类名的情况下对类实例执行某些操作。借用Axel Rauschmayer的博客,构造函数属性允许:

  • 类之间的比较,即a.constructor==b.constructor
  • 从现有实例创建新实例,即new a.constructor()
  • 调用另一个(超级)类的构造函数

所有这些都没有任何对类名的硬编码引用。同样,它并不是真的要被覆盖。为了回应上述评论,我从未真正见过有人在野外推翻它。