0
点赞
收藏
分享

微信扫一扫

JS继承实现方式

萨科潘 2022-04-16 阅读 95

一、原型继承

让父类的属性和方法在子类实例的原型链上。
特点:

  1. 不像其他语言中的继承一样(其它语言的继承一般是拷贝继承,也就是子类继承父类,会把父类中的属性和方法拷贝一份到子类中,供子类的实例调取使用),它是把父类的原型放到子类实例的原型链上,实例想调取这些方法,是基于__ proto __原型链查找机制完成的
  2. 子类可以重写父类上的方法(这样会导致父类其他的实例也受到影响)
  3. 父类中私有或者公有的属性方法,最后都会变成子类中公有的属性和方法。
    在这里插入图片描述
function A(x){
    this.x = x
}
A.prototype.getX = function(){
    console.log(this.x)
}
function B(y){
    this.y = y
}
B.prototype = new A(200)
B.prototype.construtor = B
B.prototype.getY = function(){
    console.log(this.y)
}
let b1 = new B(100)
console.log(b1.y)
b1.getY()
b1.getX()

二、call继承

Child方法中把Parent当做普通函数执行,让Parent中的this指向Child的实例,相当于给Child的实例设置了很多私有的属性或者方法
特点:

  1. 只能继承父类私有的属性或者方法(因为是把Parent当做普通函数执行,和其原型上的属性和方法没有关系)
  2. 父类私有的变为子类私有的
function A(x){ 
    this.x = x
}
A.prototype.getX = function(){
    console.log(this.x)
}
function B(y){
    A.call(this,300)   // b.x = 300
    this.y = y
}

B.prototype.getY = function(){
    console.log(this.y)
}
let b1 = new B(200)
console.log(b1.y)   // 200
console.log(b1.x)   // 300
b1.getY()          // 200

三、寄生组合继承

call继承 + 类似于原型继承
特点:父类私有和公有的分别是子类实例的私有和公有属性方法(推荐)
在这里插入图片描述

function A(x){
    this.x = x
}
A.prototype.getX = function(){
    console.log(this.x)
}
function B(y){
    A.call(this,300)   // b.x = 300
    this.y = y
}
// Object.create(OBJ)   :创建一个空对象,让空对象的__proto__指向OBJ
B.prototype = Object.create(A.prototype)
B.prototype.constructor = B
B.prototype.getY = function(){
    console.log(this.y)
}
let b1 = new B(200)

四、ES6继承

class Parent{
	constructor(){
		this.age = 18
	}
}
class Child extends Parent{
	constructor(){
		super();
		this.name = '张三'
	}
}
let o1 = new Child()
console.log(o1,o1.name,o1.age)
举报

相关推荐

0 条评论