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