gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 05:16:47 26 4
gpt4 key购买 nike

我可以使用“constructor”属性来检测 JavaScript 中的类型吗?或者有什么我应该知道的。

例如:var a = {}; a.构造函数名称;//输出“对象”

var b = 1; b.构造函数名称;//输出“数字”

var d = new Date(); d.构造函数名称;//输出“日期”而不是对象

var f = new Function(); f.构造函数名称;//输出“函数”而不是对象

只有在参数上使用它时 arguments.constructor.name;//像第一个例子一样输出对象

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

Object.prototype.toString.call({})

最佳答案

您可以使用 typeof , 但它返回 misleading results有时。相反,使用 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

关于javascript - 我可以使用 constructor.name 来检测 JavaScript 中的类型吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7039260/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com