我可以使用 constructor.name 来检测 JavaScript 中的类型吗
我可以使用“构造函数”属性来检测 JavaScript 中的类型吗? 或者有什么我应该知道的事情吗?
例如:var a = {}; a.构造函数.名称; // 输出“Object”
或 var b = 1; b.构造函数名称; // 输出“Number”
或 var d = new Date(); d.构造函数名称; // 输出“Date”而不是 Object
或 var f = new Function(); f.构造函数.名称; 输出“Function”而不是 Object
//仅当在参数上使用时才 arguments.constructor.name; //像第一个示例一样输出对象
我经常看到开发人员使用:Object.prototype.toString.call([])
或
Object.prototype.toString.call({} )
Can I use the "constructor" property to detect types in JavaScript?
Or is there something I should know about it.
For example: var a = {}; a.constructor.name; // outputs "Object"
or var b = 1; b.constructor.name; // outputs "Number"
or var d = new Date(); d.constructor.name; // outputs "Date" not Object
or var f = new Function(); f.constructor.name; // outputs "Function" not Object
only if use it on arguments arguments.constructor.name; //outputs Object like first example
I see quite often developers using: Object.prototype.toString.call([])
or
Object.prototype.toString.call({})
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
typeof
,但它返回 误导 有时会出现结果。相反,请使用Object.prototype.toString.call(obj)
,它使用对象的内部[[Class]]
属性。您甚至可以为它创建一个简单的包装器,因此它的行为类似于typeof
:不要使用
obj.constructor
因为它会被更改,尽管您可能< /em> 可以使用instanceof
来查看是否正确:You can use
typeof
, but it returns misleading results sometimes. Instead, useObject.prototype.toString.call(obj)
, which uses the object's internal[[Class]]
property. You can even make a simple wrapper for it, so it acts similar totypeof
:Don't use
obj.constructor
because it be changed, although you might be able to useinstanceof
to see if it is correct:您可以使用
typeof
例如:
typeof("Hello")
You can use
typeof
Ex:
typeof("Hello")