JavaScript instanceof vs typeof

Posted SolidMango

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaScript instanceof vs typeof相关的知识,希望对你有一定的参考价值。

Use instanceof for custom types
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
‘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
/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

以上是关于JavaScript instanceof vs typeof的主要内容,如果未能解决你的问题,请参考以下文章

每日一博 - instanceof vs isInstance vs isAssignableFrom

markdown instanceof vs typeof

JS == vs ===, typeof vs instanceof

instanceof vs isAnX()

javascript typeof 和 instanceof 的区别和联系

理解Javascript_07_理解instanceof实现原理