获取自定义对象构造函数函数名
get custom objects constructor function name
前几天我做了一个小控制台应用程序,我想在控制台中的值之前打印数据类型。
我希望在使用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 );
相关文章:
- 对使用函数构造函数创建的函数的内部引用
- 获取使用函数构造函数创建的函数的名称
- JavaScript 访问函数构造函数中的“this”
- JavaScript中的对象与函数构造函数
- 为什么实例构造函数指向最上面的函数构造函数对象
- 是否可以在函数构造函数中识别哪个对象调用它,并在错误的对象调用时中止创建
- Javascript新函数构造函数没有't返回所需的值
- Crockford 伪经典继承部分中的函数构造函数
- Jasmine:如何在ES6上监视导入的函数/构造函数
- 请解释有关 JavaScript 中的原型属性和函数构造函数的详细信息
- 主干.js - n捕获异常:语法错误:函数构造函数:无法编译函数
- 为什么使用函数构造函数创建的 Javascript 函数无法访问在其外部定义的其他函数
- 从全局范围内的另一个函数 - Javascript 调用函数构造函数的方法
- Javascript - 在闭包中使用函数构造函数是一个坏主意吗?
- Javascript - 为什么“函数构造函数”被称为“函数构造函数”
- 高级语法:“0[构造函数][构造函数]()()” - 它如何计算代码
- 函数构造函数中的局部变量
- 带有setTimeout的函数构造函数
- 如何使用exports或module.exports将函数构造函数对象方法与原型封装在单个模块中
- 如何正确映射函数构造函数