【发布时间】: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 Thing。Thing.hasOwnProperty("name")===false所以,该函数的.name来自Function.prototype。但是,Thing.prototype在Function.prototype前面,因此它所具有的任何冲突都会掩盖继承。看到直接 function.prototypes 出现在实例之外很奇怪,但这有意义吗? -
感谢您解释@dandavis,我知道现在问题出在哪里。如果您回答,它将被接受。
标签: javascript object constructor prototype