我可以使用constructor.name检测JavaScript中的类型吗

我可以使用constructor.name检测JavaScript中的类型吗,javascript,types,detection,Javascript,Types,Detection,我可以使用构造函数属性来检测JavaScript中的类型吗? 还是有什么我应该知道的 例如:vara={};a、 constructor.name//输出对象 或var b=1;b、 constructor.name//输出编号 或var d=新日期();d、 constructor.name//输出日期非对象 或var f=新函数();f、 constructor.name//输出功能不是对象 仅当在参数arguments.constructor.name//像第一个示例一样输出对象 我经常看

我可以使用构造函数属性来检测JavaScript中的类型吗? 还是有什么我应该知道的

例如:
vara={};a、 constructor.name//输出对象

var b=1;b、 constructor.name//输出编号

var d=新日期();d、 constructor.name//输出日期非对象

var f=新函数();f、 constructor.name//输出功能不是对象

仅当在参数
arguments.constructor.name//像第一个示例一样输出对象

我经常看到开发人员使用:
Object.prototype.toString.call([])


Object.prototype.toString.call({})
您可以使用
typeof
例如:
typeof(“Hello”)
您可以使用,但它有时会返回。相反,使用
Object.prototype.toString.call(obj)
,它使用对象的内部
[[Class]]]
属性。您甚至可以为它制作一个简单的包装器,因此它的行为类似于
typeof

function TypeOf(obj) {
  return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
}

TypeOf("String") === "string"
TypeOf(new String("String")) === "string"
TypeOf(true) === "boolean"
TypeOf(new Boolean(true)) === "boolean"
TypeOf({}) === "object"
TypeOf(function(){}) === "function"
不要使用
obj.constructor
,因为它可能会更改,尽管您可以使用
instanceof
查看它是否正确:

function CustomObject() {
}
var custom = new CustomObject();
//Check the constructor
custom.constructor === CustomObject
//Now, change the constructor property of the object
custom.constructor = RegExp
//The constructor property of the object is now incorrect
custom.constructor !== CustomObject
//Although instanceof still returns true
custom instanceof CustomObject === true

typeof实际上不会那么精确,因为
alert(typeof new Number())//Object
同意,因为JavaScript不是一种类型化语言,你不能期望它的类型是精确的:)不,JavaScript是一种松散类型的语言。你确定吗
typeof
operator是最好的选择,可以确定变量是否被指定(或者它是否存在,也有一些问题),但是如果我有这样的问题:
var a=function(){};var b=新的a();a型//输出新数组()的对象
类型//输出对象
。那么,我如何才能准确地使用它呢?@Gruntee[需要引证]在IE11中对我来说很好