typeof和instanceof有什么区别,何时应该使用另一个? [英] What is the difference between typeof and instanceof and when should one be used vs. the other?

查看:191
本文介绍了typeof和instanceof有什么区别,何时应该使用另一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的特定情况下:

callback instanceof Function

typeof callback == "function"

甚至重要,有什么区别?

does it even matter, what's the difference?

其他资源:

JavaScript-Garden typeof vs instanceof

JavaScript-Garden typeof vs instanceof

推荐答案

使用 instanceof 获取自定义类型:



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 



使用 typeof 进行简单构建in types:



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



使用 instanceof 进行复杂构建类型:



Use instanceof for complex built in types:

/regularexpression/ instanceof RegExp; // true
typeof /regularexpression/; // object

[] instanceof Array; // true
typeof []; //object

{} instanceof Object; // true
typeof {}; // object

最后一个有点棘手:

typeof null; // object

这篇关于typeof和instanceof有什么区别,何时应该使用另一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆