获取自定义对象构造函数名称

时间:2016-01-08 21:30:16

标签: javascript object constructor prototype

前几天我做了一个小的控制台应用程序,我想在控制台中的值之前打印数据类型。

我想在使用new关键字创建Object时检索构造函数的名称,但是我遇到了困难。

还有其他方法可以检索构造函数名称。我无法使用自定义构造函数属性引用修改原型。



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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

不要将对象分配给原型, 将每个属性分配给现有的prototype-object

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