构造函数 vs typeof 来检测 JavaScript 中的类型

alp*_*pav 5 javascript constructor types typeof detection

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

所以代替 typeof callback == "function"

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

对我来说,在运行时性能和编码安全性方面,与内存指针的比较总是比与字符串的比较要好。

为什么不使用构造函数来检测所有类型而忘记丑陋typeof

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

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.
Run Code Online (Sandbox Code Playgroud)

如果可以依赖字符串实习,那么运行时性能优势就会消失。但安全编码优势仍然存在。

Ste*_*her 4

instanceof更好,因为它适用于继承的构造函数。.constructor是对象上的可变属性,因此检查并不是一件好事,因为人们可以简单地更改它。你无法改变instanceof某些东西。

const x = new Date();
console.log("Date Constructor", x.constructor);
x.constructor = "herpderpderp";
console.log("Date Constructor", x.constructor);
Run Code Online (Sandbox Code Playgroud)