【问题标题】:get custom objects constructor function name获取自定义对象构造函数名称
【发布时间】:2016-01-08 21:30:15
【问题描述】:

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

我想在使用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>

【问题讨论】:

  • 没有你的原型代码,thing.constructor.name 工作得很好。顺便说一句,这是因为 name 必须一直从 Function.prototype 继承,所以如果你定义一个自定义原型,它会影响 name 属性的低重要性继承。
  • 啊,有道理。但是为什么这会阻止thing.constructor.name 工作
  • 因为它覆盖了现在从 Object 继承的构造函数属性。并指向 Object 函数/构造函数
  • 好的,所以thing.constructor=== function ThingThing.hasOwnProperty("name")===false 所以,该函数的 .name 来自 Function.prototype。但是,Thing.prototypeFunction.prototype 前面,因此它所具有的任何冲突都会掩盖继承。看到直接 function.prototypes 出现在实例之外很奇怪,但这有意义吗?
  • 感谢您解释@dandavis,我知道现在问题出在哪里。如果您回答,它将被接受。

标签: javascript object constructor prototype


【解决方案1】:

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

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

【讨论】:

  • 感谢您的回答。这对我来说也很有意义。通常我使用extend(thing.prototype, { ... stuff ... }) 而不是thing.prototype = {... stuff ...},所以我从来没有遇到过这个问题,但感谢您指出。
猜你喜欢
  • 2019-05-17
  • 2018-02-23
  • 1970-01-01
  • 2012-10-08
  • 2016-06-10
  • 1970-01-01
  • 2011-02-13
  • 1970-01-01
相关资源
最近更新 更多