js中的五个继承方法

js中的继承方法:

1、构造函数方法继承(用call()方法

function Father(a,b) {

        this.a = a

        this.b = b

}

function Children () {

        Father.call(this, a, b) // 将父构造函数的this指向子构造函数的实例,从而实现继承

}

缺点:1、无法继承父构造函数的原型对象的方法,2、每次创建子构造函数实例都会添加父构造函数的方法,导致占用内存大

2、原型链继承

function Father(a,b) {

        this.a = a

        this.b = b

}

function Children (c) {

        this.c = c

}

Children.prototype = new Father() // 将子构造函数的原型对象指向父构造函数的实例

Children.prototype.constructor = Children // 作用是让constructor 重新指向子构造函数

这种方式会重写子构造函数的原型对象,(Children.prototype.constructor === Father)

缺点:

  1. 可以直接修改父构造函数属性值
  2. 无法向父构造函数传递参数

注意:给子构造函数的原型对象上添加方法时必须在Children.prototype = new Father()之后,否则无法调用

3、组合继承

function Father(a,b) {

        this.a = a

        this.b = b

}

function Children () {

        Father.call(this, a, b) // 继承父构造函数的属性方法同时可以传参

}

Children.prototype = new Father() // 继承父构造函数的属性方法以及原型对象的属性和方法

Children.prototype.constructor = Children // 作用是让constructor 重新指向子构造函数

缺点:父构造函数的属性和方法会被绑定和执行两次

4、寄生式组合继承优化组合式存在的缺点

function Father(a,b) {

        this.a = a

        this.b = b

}

function Children () {

        Father.call(this, a, b)  // 继承父构造函数的属性方法同时可以传参

}

function Super () {}  // 添加一个媒介Super构造函数

Super.prototype = Father.prototype  // Super构造函数的原型对象指向父构造函数的原型对象,实现继承父构造函数的原型对象的属性和方法,同时不用二次绑定父构造函数的属性和方法

Children.prototype = new Super ()  // 将子构造函数的原型对象指向Super构造函数实例

Children.prototype.constructor = Children

5、拷贝继承

function Person(age) {

        This.age =  age

}

function Student(name, age) {

        var person = new Person(age);

        for (var key in person) {

                this.name = name;

                if. (person . hasOwnProperty(key)) {  // 不是Person原型对象的属性

                        this[key] = person[key];

                }else{

                        Student . prototype[key] = person[key];  // 是Person原型对象的属性,添加到Student构造函数的原型对象上

                }

        }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值