概述
instanceof运算符用来判断一个构造函数的prototype属性所指向的对象是否存在另外一个要检测对象的原型链上
语法
obj instanceof object;//true 实例obj在不在object构造函数中
描述
instanceof 运算符用来检测 constructor.prototype 是否存在于参数 object 的原型链上。
实例
1.instanceof的普通的用法,obj instanceof object 检测object.prototype是否存在于参数obj的原型链上。
person的原型在p的原型链中
function person(){};
var p =new person();
console.log(p instanceof person);//true2.继承中判断实例是否属于它的父类
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);//true3.复杂用法
这里的案例要有熟练的原型链的认识才能理解
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总结
对应上述规范做个函数模拟a instanceof b:
function _instanceof(a, b) {
var o = b.prototype;// 取b的显示原型
a = a.__proto__;// 取a的隐式原型
while (true) {
//object.prototype.__proto__ === null
if (a === null)
return false;
if (o === a)// 这里重点:当 o 严格等于 a 时,返回 true
return true;
a = a.__proto__;
}
}到此这篇关于javascript中instanceof运算符的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持代码网。
发表评论