通俗易懂的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可以用来判断原型和实例的继承关系

  1. instanceof可以用来检测某个对象是否为另一个对象的实例
var Father = function() {};
var instance = new Father();
instance instanceof Father  // true
  1. 其实只要在instanceSon的原型链上都会返回true

     instanceSon instanceof Object  //true
     instanceSon instanceof Father  //true
     instanceSon 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__ === null
        if(a === null)
        return false
        if(a === C)
        return true
        a = 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
  • 7
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 17
    评论
评论 17
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值