简体   繁体   中英

Checking the equality of different kind of functions in Javascript

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

On running the above code in the console , the final statement gives false. whereas, typeof all the 3 functions returns function. I know that there are some weird parts in javascript with typeof ..Can you guys explain this please..

The problem has nothing to do with the types not being equal but the fact that:

a === b === c

is interpreted as:

(a === b) === c

So this means that the first test typeof a === typeof b is resolved as true and now you perform an equality check like true === typeof window.c .

You can solve the problem by rewriting the condition to:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM