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>
沒有你的原型代碼,'thing.constructor.name '工作得很好。這是因爲'name'必須從Function.prototype一路繼承,所以如果你定義了一個自定義的原型,它會爲name屬性隱藏這個低重要性的繼承。 – dandavis
啊,這很有道理。但爲什麼會阻止'thing.constructor.name'工作 – synthet1c
,因爲它覆蓋了現在從Object繼承的構造函數屬性。並指向Object函數/構造函數 – Thomas