检查类型构造函数

时间:2013-08-22 08:08:56

标签: javascript inheritance prototype

我正在使用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派生的新类型,并能够在运行时检查实例化对象的类型。)

1 个答案:

答案 0 :(得分:1)

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 );
相关问题