Use instanceof
for custom types:(将instanceof
用于自定义类型:)
var ClassFirst = function () {};
var ClassSecond = function () {};
var instance = new ClassFirst();
typeof instance; // object
typeof instance == 'ClassFirst'; // false
instance instanceof Object; // true
instance instanceof ClassFirst; // true
instance instanceof ClassSecond; // false
Use typeof
for simple built in types:(对于简单的内置类型,请使用typeof
:)
'example string' instanceof String; // false
typeof 'example string' == 'string'; // true
'example string' instanceof Object; // false
typeof 'example string' == 'object'; // false
true instanceof Boolean; // false
typeof true == 'boolean'; // true
99.99 instanceof Number; // false
typeof 99.99 == 'number'; // true
function() {} instanceof Function; // true
typeof function() {} == 'function'; // true
Use instanceof
for complex built in types:(将instanceof
用于复杂的内置类型:)
/regularexpression/ instanceof RegExp; // true
typeof /regularexpression/; // object
[] instanceof Array; // true
typeof []; //object
{} instanceof Object; // true
typeof {}; // object
And the last one is a little bit tricky:
(而最后一个有点棘手:)
typeof null; // object
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…