码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript instanceof vs typeof

时间:2017-01-07 01:29:50      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:number   ber   java   ceo   regular   soft   font   reg   sse   

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

标签:number   ber   java   ceo   regular   soft   font   reg   sse   

原文地址:http://www.cnblogs.com/pugang/p/6257948.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!