关于继承

本文深入解析JavaScript中的六种继承方式,包括类式继承、构造函数继承、组合继承、寄生式继承、组合寄生和ES6继承。每种方式的特点、实现及缺陷被详细讨论,帮助读者理解并掌握JavaScript继承的多样性和复杂性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

继承前提---- 继承分为两种:类与类之间的继承,类创造实例对象

funtion parent(){
    //私有属性
    var name ;
    //私有方法
    var addName = function(){};
    //公有属性
    this.sex;
    //公有方法
    this.addSex = function(){};
}
parent.prototype = {
    //共有属性(原型属性)
    age: 11,
    //共有方法
    setAge: function(){}
}复制代码

1、类式继承:(类与类之间的继承)

function parent(){     this.name = [];
}
parent.prototype = {
      age: 12
}

//声明子类
function child(){}
child.prototype = new parent();
//缺陷:
//1、父类的公共属性为引用类型时,子类生成的实例对象之间的属性会相互影响
let child_example1 = new child();
let child_example2 = new child();
console.log(child_example1.name);//[]
console.log(child_example2.name);//[]
child_example1.name.push(1);
console.log(child_example2.name);//[1]
//2、子类实例无法初始化父类原型中的属性和方法

复制代码

2、构造函数继承:(类与类之间的继承)

function parent(name){
    this.name = name;
}
parent.prototype = {
    sex: '男'
}
function child(){
    parent.call(this,'ltp');
}
let child_example = new child();
console.log(child.prototype.name);
console.log(child_example.sex);//undefained
console.log(child_example.name);//'ltp'
//缺陷:子类的实例对象和子类无法访问父类原型中的属性和方法
复制代码

3、组合继承(类式继承和构造函数继承结合)

function parent(){
    this.name = 'ltp';
}
parent.prototype = {
    age: 11
}
function child(){
    parent.call(this);
}
child.prototype = new parent();
//弥补了构造函数继承和类式继承的缺点复制代码

4、寄生式继承

let origin = {};
function inherit(origin){
   function F(){}
    //方法借用
    F.prototype = origin;
    return new F();
}
let parent = inherit(origin);复制代码

5、组合寄生

function interit(target,origin){
    function F(){}
    F.prototype = new origin();
    F.constractor = target;
    target.prototype = new F();
}

复制代码

6、ES6继承

class A {
    constructor(name){
        this.name = name;
    }
}
class B extends A {
    constructor(sex,name){
        super(name);
        this.sex = sex;
        this.method1 = this.method1.bind(this);
    }
    method1 () {
        console.log('已继承');
    }
}
let a = new A('ltp');
console.log(a);
let b = new B('ltp','男');
console.log(b);
b.method1();复制代码

super()指向父类,可以向父类实现传参,constructor是构造方法

在ES6继承中,类没有私有变量和私有方法,可通过new实现对类的实例化,extends实现类与类之间的继承


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值