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

get custom objects constructor function name

本文关键字:函数 构造函数 对象 自定义 获取      更新时间:2023-09-26

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

我希望在使用new关键字创建Object时检索Constructor函数的名称,但我遇到了困难。

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

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>

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

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