typeof
用于判断数据类型,返回值为6个字符串,分别为string、Boolean、number、function、object、undefined
。
var a = [34,4,3,54],
b = 34,
c = 'adsfas',
d = function(){console.log('我是函数')},
e = true,
f = null,
g;
console.log(typeof(a));//object
console.log(typeof(b));//number
console.log(typeof(c));//string
console.log(typeof(d));//function
console.log(typeof(e));//boolean
console.log(typeof(f));//object
console.log(typeof(g));//undefined
但是你可能会发现,typeof在判断null、array、object以及函数实例(new + 函数)时,得到的都是object。这使得在判断这些数据类型的时候,得不到真是的数据类型。由此引出instanceof。
instanceof
instance
中文翻译为实例,因此 instanceof
的含义就不言而喻,判断该对象是谁的实例,同时我们也就知道 instanceof
是对象运算符。
这里的实例就牵扯到了对象的继承,它的判断就是根据原型链进行搜寻,在对象obj1的原型链上如果存在另一个对象obj2的原型属性,那么表达式(obj1 instanceof obj2)返回值为true;否则返回false。
实例
instanceof
的普通的用法,obj instanceof Object
检测Object.prototype
是否存在于参数obj
的原型链上。
Person
的原型在p
的原型链中
function Person(){};
var p =new Person();
console.log(p instanceof Person);//true
- 继承中判断实例是否属于它的父类
Student和Person都在s的原型链中
function Person(){};
function Student(){};
var p =new Person();
Student.prototype=p;//继承原型
var s=new Student();
console.log(s instanceof Student);//true
console.log(s instanceof Person);//true
- 复杂用法
这里的案例要有熟练的原型链的认识才能理解
function Person() {}
console.log(Object instanceof Object); //true
//第一个Object的原型链:Object=>
//Object.__proto__ => Function.prototype=>Function.prototype.__proto__=>Object.prototype
//第二个Object的原型:Object=> Object.prototype
console.log(Function instanceof Function); //true
//第一个Function的原型链:Function=>Function.__proto__ => Function.prototype
//第二个Function的原型:Function=>Function.prototype
console.log(Function instanceof Object); //true
//Function=>
//Function.__proto__=>Function.prototype=>Function.prototype.__proto__=>Object.prototype
//Object => Object.prototype
console.log(Person instanceof Function); //true
//Person=>Person.__proto__=>Function.prototype
//Function=>Function.prototype
console.log(String instanceof String); //false
//第一个String的原型链:String=>
//String.__proto__=>Function.prototype=>Function.prototype.__proto__=>Object.prototype
//第二个String的原型链:String=>String.prototype
console.log(Boolean instanceof Boolean); //false
//第一个Boolean的原型链:Boolean=>
//Boolean.__proto__=>Function.prototype=>Function.prototype.__proto__=>Object.prototype
//第二个Boolean的原型链:Boolean=>Boolean.prototype
console.log(Person instanceof Person); //false
//第一个Person的原型链:Person=>
//Person.__proto__=>Function.prototype=>Function.prototype.__proto__=>Object.prototype
//第二个Person的原型链:Person=>Person.prototype