一. typeof
1.typeof的作用:用来判断数据类型。可以用来判断string,number,boolean,function,object,symbol,undefined这些数据类型。但是并不能判断到底是什么类型的Object。例如:
var a=[1,2,3];
console.log(typeof a);//object
2.typeof的原理:
js 在底层存储变量的时候,会在变量的机器码的低位1-3位存储其类型信息:
对象:000 浮点数:010 字符串:100 布尔:110 整数:1
null:全是0(因此会被误以为是对象类型)undefined:用 −2^30 整数来表示
因此要避免用typeof 判断null
3 Object.prototype.toString.call(A)也能用来判断A的数据类型
console.log(Object.prototype.toString.call(1));
console.log(Object.prototype.toString.call([1,2]));
console.log(Object.prototype.toString.call('1'));
console.log(Object.prototype.toString.call(function(){}));
console.log(Object.prototype.toString.call(null));
console.log(Object.prototype.toString.call({lxt:'student'}));
输出:
二. instanceof
A instanceof B:在实例对象A的原型链中是否可以找到构造函数B的原型对象( prototype 属性)
我自己实现了一下:
var Person = function () {
}
var p1 = new Person();
function isinstance(a, b) {
while (a !== null) {
if (a.__proto__ === b.prototype) {
return true;
} else {
a = a.__proto__
}
}
return false;
}
console.log(isinstance(p1, Object));//true
console.log(isinstance(p1, Person));//true
作者:nicole_zhang
链接:https://juejin.im/post/5b0b9b9051882515773ae714
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。