检查 Javascript 中不同类型函数的相等性

Checking the equality of different kind of functions in Javascript

本文关键字:函数 同类型 Javascript 检查      更新时间:2023-09-26
function a(){ return true; }
var b = function(){ return true; };
window.c = function(){ return true; };

console.log(typeof a);//returns funtion
console.log(typeof b);  //returns funtion
console.log(typeof window.c);   //returns funtion
typeof a === typeof b === typeof window.c  //returns false

在控制台中运行上述代码时,final 语句给出 false。 而所有 3 个函数的类型返回函数。我知道javascript中有一些奇怪的部分,类型为..你们能解释一下吗..

问题与类型不相等无关,而与以下事实有关:

a === b === c

被解释为:

(a === b) === c

因此,这意味着第一个测试typeof a === typeof b解析为true,现在您执行像true === typeof window.c一样的相等性检查。

您可以通过将条件重写为:

(typeof a === typeof b) && (typeof b === typeof window.c)