最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Can i use constructor.name to detect types in JavaScript - Stack Overflow

programmeradmin2浏览0评论

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({})

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({})

Share Improve this question edited Nov 21, 2021 at 12:11 orustammanapov asked Aug 12, 2011 at 11:11 orustammanapovorustammanapov 1,8626 gold badges28 silver badges47 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

You can use typeof, but it returns misleading results sometimes. Instead, use Object.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 to 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"

Don't use obj.constructor because it be changed, although you might be able to use instanceof to see if it is correct:

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

You can use typeof Ex: typeof("Hello")

发布评论

评论列表(0)

  1. 暂无评论