确定类型的三种方式:
typeof
用来确定原始类型,更准确的说用来确定变量是字符串,数值,布尔值和undefined。ES6后多了个Symbol。因为如果对象是null,typeof返回的是object
let a = 3;
let b = '3';
let c = true;
let d = undefined;
let e = {} ;
let f = ['1'] ;
let g = new Object();
let h = Symbol('bar');
let i = null;
console.log(typeof a);//number
console.log(typeof b);//string
console.log(typeof c);//boolean
console.log(typeof d);//undifined
console.log(typeof ddd);//未定义也是 undefined
console.log(typeof e);//object
console.log(typeof f);//object
console.log(typeof g);//object
console.log(typeof h);//symbol
console.log(typeof i);//object
instanceof
instanceof是个运算符。用来检测constructor.prototype(constructor是构造函数)是否在参数object的原型链上。
所以instanceof是不能判定原始类型的。原始类型就是个值,不存在prototype属性。
接下来还是代码说话
let g = new Object();
console.log('g:',g instanceof Object);//g:true
//这里实际是什么操作呢?
//实际是Object.getPrototypeOf(g) === Object.prototype
console.log(Object.getPrototypeOf(g) === Object.prototype);
//由于是构造函数,也可以这样
function test(){};
let o = new test();
console.log(o instanceof test);//true
console.log(Object.getPrototypeOf(o) === test.prototype);//true
Object.prototype.toString.apply(obj)
这个其实记得就好啦,我们可以看看Object的属性打印Object.prototype

最后上个方法就结束吧,有关Object的内置对象,js的原型链,apply的具体使用和含义我们不在这里叙述,会另开篇章
export function getType (argu) {
let type = Object.prototype.toString.apply(argu)
return type
}
本文介绍了JavaScript中三种类型检测的方法:typeof、instanceof以及Object.prototype.toString.apply。详细解释了每种方法的工作原理及其适用场景。

2977

被折叠的 条评论
为什么被折叠?



