简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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