简体   繁体   English

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

[英]get custom objects constructor function name

I made a little console application the other day and I'm wanting to print the data type before the value in the console. 前几天我做了一个小的控制台应用程序,我想在控制台中的值之前打印数据类型。

I would like when an Object is created with the new keyword to retrieve the name of the Constructor function, but I'm having difficulty. 我想用new关键字创建一个Object来检索Constructor函数的名称,但是我遇到了困难。

Is there any other way to retrieve the constructor name. 还有其他方法可以检索构造函数名称。 I would not be able to modify the prototype with a custom constructor property reference. 我将无法使用自定义构造函数属性引用来修改原型。

 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> 

Don't assign a Object to the prototype, assign each property to the existing 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 );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM