typeof

问题:typeof nullobject。引用类型数据用typeof来判断的话,除了function会被识别出来之外,其余的都输出object

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
typeof str     // "string" 字符串
typeof num // "number" 数值
typeof array // "object" 对象(可以和函数区别开)
// 👆注意,数组也是一个对象
typeof date // "object" 对象
typeof func // "function" 函数
typeof symbol // "symbol"
typeof null // object

// 对于未声明的变量
typeof test // undefined 未定义

// 对于声明过,但是未赋值的变量
let message;
typeof message // undefined 也是未定义,因为只声明但没有赋值

instanceof

原理:左边是一个实例对象,右边是一个构造函数,instanceof会检查构造函数的原型对象prototype是否在左边对象的原型链上,有则返回true,否则返回false.

问题:instanceof 可以准确地判断复杂引用数据类型,但是不能正确判断基础数据类型。同时只能判断是否是某个类型,不能检测类型。

1
2
3
array instanceof Array   // true
date instanceof Date // true
func instanceof Function // true

constructor

不能判断null,undefined。

如果创建一个对象,更改它的原型,这种方式也变得不可靠了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
(2).constructor === Number // true
(true).constructor === Boolean // true
('str').constructor === String // true
([]).constructor === Array // true
(function() {}).constructor === Function // true
({}).constructor === Object // true

// 反例
function SuperType(){}
function SubType(){}
SubType.prototype = new SuperType();

let sub = new SubType();

sub.constructor === SubType // false
sub.constructor === SuperType // true
sub.constructor === Object // false

Object.prototype.toString.call()

啥都可以判断,就是写着麻烦

1
2
3
4
5
6
7
Object.prototype.toString.call(str) === '[object String]'    // true
Object.prototype.toString.call(num) === '[object Number]' // true
Object.prototype.toString.call(array) === '[object Array]' // true
Object.prototype.toString.call(date) === '[object Date]' // true
Object.prototype.toString.call(func) === '[object Function]' // true
Object.prototype.toString.call(symbol) === '[object Symbol]' // true
Object.prototype.toString.call(new Error()) === '[object Error]' //true