构造函数与typeof来检测JavaScript中的类型 [英] constructor vs typeof to detect type in JavaScript

查看:71
本文介绍了构造函数与typeof来检测JavaScript中的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题中,我没有看到建议使用构造函数。

In this question I did not see suggestions to use constructor.

所以不是 typeof callback == function

我会使用回调&& (callback.constructor == Function)

对我来说,与内存指针的比较似乎总是比与字符串的比较好

To me it seems obvious that comparison to memory pointers is always better than comparison to strings in terms of both runtime performance and coding safety.

为什么不使用构造函数来检测所有类型,而忘记难看的 typeof

Why not use constructor to detect all types and forget about ugly typeof?

它适用于所有原始类型,函数和数组:

It works for all primitive types, functions and arrays:

undefined === undefined
null === null
[1,2,3].constructor == Array 
(1).constructor == Number
(true).constructor == Boolean
(()=>null).constructor == Function
'abc'.constructor == String
(new Date()).constructor == Date
else it's an object, where instanceof helps to detect it's parents if needed.

如果字符串实习,然后运行时性能优势就会消失。但是安全的编码优势仍然存在。

If string interning can be relied upon then runtime performance advantage goes away. But safe coding advantage still stays.

推荐答案

instanceOf 更好,因为它与继承的构造函数一起使用。 .constructor 是对象的可变属性,因此检查它不是一件好事,因为可以简单地对其进行更改。您不能更改 instanceOf 内容。

instanceOf is better because it works with inherited constructors. .constructor is a mutable property on an object, so it's not a good thing to check because one can simply change it. You can't change the instanceOf something.

const x = new Date();
console.log("Date Constructor", x.constructor);
x.constructor = "herpderpderp";
console.log("Date Constructor", x.constructor);

这篇关于构造函数与typeof来检测JavaScript中的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆