instanceof 用来判断构造函数的prototype属性是否出现在一个实例对象的原型链上
function instance_of(obj,Func) {
let __obj = obj.__proto__;
while(true) {
if(__obj === null) {
return false;
}
if(__obj === Func.prototype) {
return true;
}
__obj = __obj.__proto__;
}
}
没有继承关系时
function Person() {}
let p1 = new Person();
let obj = {
a:'1',
b:'2'
}
console.log('p1 instanceof Person',p1 instanceof Person);// true
console.log('p1 instanceof Object',p1 instanceof Object);// true
console.log('obj instanceof Person',obj instanceof Person);// false
- 执行 p1 instanceof Person代码时
- 会比较p1.__ proto __ === Person.prototype的值,结果是相等的,所以返回true
- 执行 p1 instanceof Object代码时
- 比较p1.__ proto __ === Object.prototype的值,返回false
- 继续比较p1.__ proto __ .__ proto __ === Object.prototype的值,返回true
- 执行 obj instanceof Person代码时
- 比较obj.__ proto __ === Object.prototype的值,返回false
- _ obj.__ proto __ . __ proto __ ===null,所以返回false
当发生了继承关系时,是如何实现的呢
function Person() {
this.name='person';
this.age=1;
}
let p1 = new Person();
function Children() {
Person.call(this);
this.score=100;
}
let child = new Children();