为何而来
javaScript的变量是松散类型的,所谓的松散类型就是可以用来保存任何类型的数据。如果需要检验变量的数据类型,我们就需要用到typeof和instanceof。
有何区别
typeof
-
typeof能够检测基本数据类型,返回的是字符串
基本数据类型:Number,String,Boolean,Undefined,Symbol,Null
console.log(typeof 42); > "number" console.log(typeof 'name'); >"string" console.log(typeof true); >"boolean" console.log(typeof noSay); >"undefined" console.log(typeof Symbol()); >"symbol" console.log(typeof null); >"object"注:typeof null会返回"object",因为null被认为是一个空的对象引用
-
typeof如果检测复杂的数据类型,返回的都是"object"
console.log(typeof {a: 1}); >"object" console.log(typeof [1, 2, 4]); >"object" console.log(typeof new Date()); >"object" -
typeof如果检测函数,返回的都是"function"
console.log(function() {}); >"function" console.log(typeof class C {} ); >"function" console.log(typeof Math.sin); >"function"
instanceof
instanceof运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。
// 定义构造函数
function C(){}
function D(){}
var o = new C();
o instanceof C; // true,因为 Object.getPrototypeOf(o) === C.prototype
o instanceof D; // false,因为 D.prototype 不在 o 的原型链上
o instanceof Object; // true,因为 Object.prototype.isPrototypeOf(o) 返回 true
C.prototype instanceof Object // true,同上
C.prototype = {};
var o2 = new C();
o2 instanceof C; // true
o instanceof C; // false,C.prototype 指向了一个空对象,这个空对象不在 o 的原型链上.
D.prototype = new C(); // 继承
var o3 = new D();
o3 instanceof D; // true
o3 instanceof C; // true 因为 C.prototype 现在在 o3 的原型链上
小试牛刀
如合判断一个变量是否为数组?
console.log([1,2,3,4] instanceof Array);
>true
爱上一句话
就算哭到凌晨5点,早上7点也要准时起来上班,这就是成年人的生活!