正在检查类型构造函数函数

Checking a type constructor function

本文关键字:构造函数 函数 类型 检查      更新时间:2023-09-26

我正在使用Object.create()创建新的原型,我想检查用于对象的构造函数。

OBJECT.constructor只返回继承的原型:

var mytype = function mytype() {}
mytype.prototype = Object.create( Object.prototype, { } );
//Returns "Object", where I would like to get "mytype"
console.log( ( new mytype ).constructor.name );

如何做到这一点(不使用任何外部库)?

(我的最终目标是创建从Object派生的新类型,并能够在运行时检查实例化对象的类型)。

var mytype = function mytype() {}
mytype.prototype = Object.create( Object.prototype, { } );

将新对象分配给mytype.prototype后,mytype.prototype.constructor属性将被Object.prototype.constructor覆盖,因此必须将mytype.prototype.constructor更改回mytype

mytype.prototype.constructor = mytype;

它将恢复您覆盖的原始原型对象上的.constructor属性。你应该恢复它,因为它应该在那里。

//Returns "Object", where I would like to get "mytype"
console.log( ( new mytype ).constructor.name );