SoFunction
Updated on 2025-03-01

JavaScript type judgment code analysis

Copy the codeThe code is as follows:

var is = function(obj,type){
var toString=,undefined;
return obj===null&&type==='Null'||
obj===undefined&&type==='Undefined'||
(obj).slice(8,-1)===type;
}
//The original text contains brackets to wrap each logic and operation, but according to the operator priority, brackets can be omitted
//The first line declares undefined. Personally, I understand that it is to improve performance and there is no need to query undefined in the top-level scope.


According to the explanation in ECMA-262, (), the type of the object instance will be returned, and the format "[object", class, and "]" string will be returned.
So intercept the 'class' value through slice, that is, the type value.
Where null and undefined are exceptions, because what they return is
[object Object] in IE
Standard browser [object Window].
Therefore, make a judgment separately.