2016-01-08 109 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

相关问题