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

oru*_*tam 6 javascript types detection

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

例如: var a = {}; a.constructor.name; //outputs Object

要么 var b = 1; b.constructor.name; //outputs Number

要么 var d = new Date(); d.constructor.name; //outputs Date not Object

要么 var f = new Function(); f.constructor.name; //outputs Function not Object

只有在参数上使用它 arguments.constructor.name; //outputs Object like first example

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

Object.prototype.toString.call({})

Dig*_*ane 6

您可以使用typeof,但有时会返回误导性 结果.而是使用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"
Run Code Online (Sandbox Code Playgroud)

请勿使用,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
Run Code Online (Sandbox Code Playgroud)