检测基本类型使用typeof
typeof
是检测一个变量是不是基本数据类型的最佳工具,更具体一点,typeof
是确定一个变量是字符串、数值、布尔值,还是undefined的最佳工具。
var s = 'jack'
var b = true
var i = 22
var u
var n = null
var o = new Object()
alert(typeof s) // string
alert(typeof b) // boolean
alert(typeof i) // number
alert(typeof u) // undefined
alert(typeof n) // object
alert(typeof o) // obejct
另外,typeof
检测function
会返回function
检测引用类型使用instanceof
检测引用类型使用instanceof
,因为通常我们并不是想知道某个值是对象,而是想知道它是什么类型的对象。
var person = new Object()
alert(person instanceof Object) // true
alert(person instanceof Array) // false
alert(person instanceof RegExp) // false
instanceof
会根据原型链来识别,它检测后面参数的
prototype
是否存在于前面参数的原型链上,也就是判断变量是否是给定引用类型的实例,或者说是否继承,
instanceof
会返回true
或false
。
以下代码摘自 js中typeof用法和instanceof用法
// 定义构造函数
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 的原型链上