原型和继承"/>
通俗易懂的JavaScript原型和继承
什么是原型?每个JavaScript对象创建时,都会关联一个另对象,这个对象就是他的原型,每个对象都会从原型中继承属性。
原型链
1. 每个构造函数(constructor)都有一个原型对象(prototype),
2. 原型对象都包含一个指向构造函数的指针(constructor)
3. Father.prototype.constructor === Father
4. 而实例(instance)都包含一个指向原型对象的内部指针(__protp__)
5. instance.__proto__ === constructor.prototype
假如在instance实例上查找某个属性,会首先在实例内部查找该属性,没有的话就通过__proto__去构造函数的原型对象上查找
他们通过__proto__和prototype连接实例和原型形成的链条就是原型对象
如果将原型对象指向另一个实例,即constructor1.prototpye = instance2
那么如果在instance1上查找方法getFatherName
1. 首先会在instance1上进行查找
2. 然后通过instance1.__proto__去原型对象constructor1.prototype上查找
3. 但是constructor1.prototype = instance2,所以会去instance2上查找
4. 然后再去constructor2.prototype上查找
5. 最后会一直去到Object.prototype上
他们的搜素路径就是
instance1->instance2->constructor2.prototype->Object.prototype
eg:
function Father(){this.FatherName = '阿花';
}
Father.prototype.getFatherName = function (){return this.FatherName;
}
function Son(){this.SonName = 'ahua'
}
Son.prototype.getSonName = function() {return this.SonName
}
// Son的原型对象指向Father的实例
Son.prototype = new Father();var instanceSon = new Son()
console.log(instanceSon.getFatherName()) // 阿花
console.log(instanceSon.getSonName()) // instanceSon.getSonName is not a function
// 因为在instanceSon中找不到getSonName方法时会去到其原型对象
//而Son的原型对象指向Father的实例,Father的原型对象没有getSonName方法
原型和实例的关系
instanceof
instanceof可以用来判断原型和实例的继承关系
- instanceof可以用来检测某个对象是否为另一个对象的实例
var Father = function() {};
var instance = new Father();
instance instanceof Father // true
-
其实只要在instanceSon的原型链上都会返回true
instanceSon instanceof Object //trueinstanceSon instanceof Father //trueinstanceSon instanceof Son //true
因为有原型链,可以说instanceSon是Son、Father、Object的实例
手写instanceof
Object.prototype.myInstanceof = function (constructor){const self = this;let a = self.__proto__;const C = consructor.prototype;while(true){// 当根据原型链查找到Object还没找到时,则instance肯定不在constructor的原型链上// Object.protptype.__proto__ === nullif(a === null)return falseif(a === C)return truea = a.__proto__ }
}
const aa = {}
console.log(instanceSon.myInstanceof(aa)) // false
console.log(instanceSon.myInstanceof(Son)) // true
console.log(instanceSon.myInstanceof(Father)) //true
console.log(instanceSon.myInstanceof(Object)) // true
isPrototypeOf
判断一个对象是否是另一个对象的原型,同样的只要在原型链上的原型对象都会返回true
console.log(Son.prototype.isPrototypeOf(instanceSon)) // true
console.log(Father.prototype.isPrototypeOf(instanceSon)) // true
console.log(Object.prototype.isPrototypeOf(instanceSon)) // true
console.log(aa.prototype.isPrototypeOf(instanceSon)) // false
更多推荐
通俗易懂的JavaScript原型和继承
发布评论