2016-01-08 120 views
0

我前幾天做了一個控制檯應用程序,我想在控制檯中的值之前打印數據類型。獲取自定義對象的構造函數名稱

我想用new關鍵字創建一個對象來檢索構造函數的名稱,但我有困難。

是否有任何其他方式來檢索構造函數名稱。我無法用自定義構造函數屬性引用修改原型。

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>

+1

沒有你的原型代碼,'thing.constructor.name '工作得很好。這是因爲'name'必須從Function.prototype一路繼承,所以如果你定義了一個自定義的原型,它會爲name屬性隱藏這個低重要性的繼承。 – dandavis

+0

啊,這很有道理。但爲什麼會阻止'thing.constructor.name'工作 – synthet1c

+1

,因爲它覆蓋了現在從Object繼承的構造函數屬性。並指向Object函數/構造函數 – Thomas

回答

2

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

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

感謝您的回答。這對我也很有意義。通常我使用'extend(thing.prototype,{... stuff ...})'而不是'thing.prototype = {... stuff ...}'所以我從來沒有遇到過這個,但是感謝指向出來。 – synthet1c

相關問題