簡體   English   中英

獲取自定義對象的構造函數名稱

[英]get custom objects constructor function name

前幾天我做了一個小的控制台應用程序,我想在控制台中的值之前打印數據類型。

我想用new關鍵字創建一個Object來檢索Constructor函數的名稱,但是我遇到了困難。

還有其他方法可以檢索構造函數名稱。 我將無法使用自定義構造函數屬性引用來修改原型。

 function Thing( name ){ this._name = name; } Thing.prototype = { /* I cant do these constructor: Thing, toString: function(){ return [object Thing]; }, */ name: function( name ){ return name != null ? (this._name = name) : name; } } var thing = new Thing('andrew'); // I have tried the following without success as it seems to be created by Object not Thing console.log( thing.constructor ); console.log( thing.constructor.name ); console.log( thing.constructor.toString() ); console.log( Thing ); console.log( Thing.prototype ); console.log( Object.getPrototypeOf( thing ) ); console.log( Object.prototype.toString.call(thing) ); // test whether thing is instanceof Thing console.log( 'is it a thing?', thing instanceof Thing ); 
 <script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script> 

不要將對象分配給原型,將每個屬性分配給現有的原型對象

function Thing( name ){
  this._name = name;
}

Thing.prototype.name = function( name ){
    return name != null
      ? (this._name = name)
      : name;
}

var thing = new Thing('andrew');

console.log( thing.constructor.name );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM