繁体   English   中英

检查类型构造函数

[英]Checking a type constructor function

我正在使用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.prototypemytype.prototype.constructor财产被覆盖Object.prototype.constructor所以你必须改变mytype.prototype.constructormytype

mytype.prototype.constructor = mytype;

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM