簡體   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