简体   繁体   中英

Checking a type constructor function

I am using Object.create() to create new prototypes and I would like to check the constructor function used for an object.

OBJECT.constructor only returns the inherited prototype :

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 );

How to do this (without using any external library) ?

(My end goal is to create new types derived from Object, and being able to check the types of instantiated objects at runtime).

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

After assigning a new object to mytype.prototype , mytype.prototype.constructor property is overridden by Object.prototype.constructor So you have to change mytype.prototype.constructor back to mytype

mytype.prototype.constructor = mytype;

It restores the .constructor property that was on the original prototype object that you overwrote. You should restore it because it's expected to be there.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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