JavaScript高级(九)---JavaScript的六种继承方式

1、原型继承

实现:

1

2

3

4

5

6

7

function Super(){ this.a=1 }

Super.prototype.say = function(){ console.log(‘hhh') }

function Sub(){}

Sub.prototype = new Super()

const test = new Sub()

console.log( test.say() )// hhh

优点:通过原型继承多个引用类型的属性和方法

缺点:Sub原型变成了Super的实例,如果Super的实例某个属性是引用值,该引用值就会被应用到所有Sub创建的实例中去,会有污染问题。如下

1

2

3

4

5

6

7

8

9

function Super(){ this.a=[1,2] }

function Sub(){}

Sub.prototype = new Super()

const test1 = new Sub()

test1.a.push(3)

console.log(test1.a)// [1,2,3]

const test2 = new Sub()

console.log(test2.a)// [1,2,3]

2、盗用构造函数

实现:构造函数模式+call

1

2

3

4

5

6

7

function Super = function(){ this.a = 1 }

function Sub = function(){

       Super.call(this)

       this.b = 2

}

const test = new Sub()

优点:每个实例都会有自己的a属性,哪怕是引用值也不会被污染

缺点:Super构造函数中的方法在每个实例上都要创建一遍(除非该方法声明提到全局);Sub的实例无法访问Super原型上的方法

3、组合继承

实现:原型继承+盗用构造函数继承

1

2

3

4

5

6

7

8

9

10

11

12

13

14

function Super(){ this.a=[1,2] }

Super.prototype.say = function(){ console.log(‘hhh') }

function Sub(){

    Super.call(this)

    this b=2

}

Sub.prototype = new Super()

  

const test1 = new Sub()

console.log( test1.say() )// hhh

test1.a.push(3)

console.log(test1.a)// [1,2,3]

const test2 = new Sub()

console.log(test2.a)// [1,2]

优点:集合了【原型继承】和【盗用构造函数继承】的优点

缺点:存在效率问题,Super始终会被调用两次

4、原型式继承

实现:

es5之前

1

2

3

4

5

6

7

8

const obj = { a:1 }

function createObj(o){

    const Fn(){}

    Fn.prototype = o

    return new Fn()

}

const test = createObj(obj)

es5之后

1

2

3

const obj = { a:1 }

const test = Object.create(obj)

优点:对一个对象进行浅克隆创建另一个对象,同时继承该对象的原型属性

缺点:由于是浅克隆,所以实例共享的对象属性如果是引用值,会受污染。如下

1

2

3

4

5

6

7

8

const obj = { a:[1,2], b:2 }

const test1 = Object.create(obj)

const test2 = Object.create(obj)

test1.a.push(3)

test1.b=3

console.log(test1.a, test2.a)// [1,2,3]  [1,2,3]

console.log(test1.b, test2.b)// 3 2

5、寄生式继承

实现:构造函数模式+工厂模式

1

2

3

4

5

6

7

8

9

10

function createObj(o){

    let clone = objectCopy(o)

    clone.say=function(){

        console.log(‘hhh')

    }

    return clone

}

const obj = { a:1 }

const test = createObj(obj)

优点:根据一个对象克隆创建另一个对象,并增强对象

缺点:同【盗用构造函数继承】方法在每个实例上都要创建一遍

注意:objectCopy是对入参对象的复制

6、寄生式组合继承

实现:盗用构造函数继承 + 原型式继承

1

2

3

4

5

6

7

8

9

10

11

function Super(){ this.a=[1,2] }

Super.prototype.say = function(){ console.log(‘hhh') }

function Sub(){

    Super.call(this)

    this b=2

}

Sub.prototype = Object.create(Super.prototype)

Sub.prototype.constructor = Sub

const test = new Sub()

优点:集合了【原型式继承】和【盗用构造函数继承】的优点,效率比【组合继承】更高。

  • 14
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值