typeof VS instanceof 详解,判断JavaScript数据类型

instanceof 运算符用来检测 constructor.prototype是否存在于参数 object 的原型链上。

typeof 操作符返回一个字符串,表示未经计算的操作数的类型。

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 

1.对于简单的内建类型使用typeof:

'example string' instanceof String; // false
typeof 'example string' == 'string'; // true

'example string' instanceof Object; // false
typeof 'example string' == 'object'; // false

(function() {
    
    }) instanceof Function; // true
typeof function() {
    
    } == 'function'; // true

typeof 对于原始类型来说,除了 null 都可以显示正确的类型
在这里插入图片描述1
typeof 对于对象来说,除了函数都会显示 'object'
1

2.对于复杂的内建类型使用instanceof:

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

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

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

在 JavaScript 最初的实现中,JavaScript 中的值是由一个表示类型的标签和实际数据值表示的。对象的类型标签是 0。由于 null 代表的是空指针(大多数平台下值为 0x00),因此,null的类型标签是 0,typeof null === 'object'

【总结】至于在真实的项目中什么时候使用它们进行数据类型比较,这取决于你要检查的可能数据类型。

如果变量可能未定义,使用typeof比较好。

typeof undefinedVariable //  "undefined"
undefinedVariable instanceof Object // throws an exception

如果变量可能为null,使用instanceof比较好。

var myNullVar = null;
typeof myNullVar; 			// "object" 
myNullVar instanceof Object; // false

3.判断JavaScript数据类型最准确的方法

我们用Object.prototype.toString的方法可以准确的判断数据类型:
obj.toString
Object.prototype.toString返回值是一个字符串,字符串里的内容固定格式为[object 判断类型的结果],前一个object全小写,后面的返回结果的首字母大写。

猜你喜欢

转载自blog.csdn.net/a1056244734/article/details/107231545