JS关于继承个个人理解

JS的继承

定义

继承,顾名思义,就是子类得到父类的东西,在js上表现为子类继承父类的私有/公有属性。
那么,如果我们想要继承,就必须有父类。

继承的分类

继承分以下几种:原型继承,call继承,组合式继承,用 Object.create实现类式继承。另外,在ES6中也有一种继承方法。
这里我只对其中几种方法进行说明,这是因为本人能力有限

原型继承

// 父类
function Dad(){
    this.x = 1;
}

Dad.prototype.getX = function(){
    return this.x;
}

// 子类
function Child(){
    this.y = 2;
}
Child.prototype = new Dad;  //子类指向父类
Child.prototype.getY = function(){
    return this.y;
}
var c1 = new Child();
alert(c1.x);    //这是继承父类的x
alert(c1.getX());    //这是继承父类的getX
alert(c1.y);    //这是继承父类的y
alert(c1.getY());    //这是自己的

call继承

也叫借用构造函数继承,只能继承父类的私有属性.例子如下:

function Dad(){     //父类
    this.x = 1;     //这是父类的私有属性
}

Dad.prototype.getX = function(){
    return this.x;
}

function Child(){
    Dad.call(this);     //这里我们让this指向父类的一个对象,然后返回
    this.y = 2;
}

var c1 = new Child();
alert(c1.x);    //输出为100,表明得到了父类的私有属性

通过Object.create实现类式继承

核心是Object.create()创建一个新对象,使用现有的对象来提供新创建的对象__proto__。例子如下

    var obj = {
        name:"wangcai"
        sat(){
            alert(this.name)
        }
    }

    obj.say();
    let newObj = Object.create(obj);    //创建新对象
    newObj.say();
    console.log(obj === newObj) //===不会改变类型,是绝对相等

组合式继承

听名字就能知道,是将别的继承方法组合起来
用Dad.call(this);继承父类的私有属性
用Child.prototype = Object.create(Dad.prototype);继承父类的公有属性
例子如下:

//父类
function Dad(){
    this.x = 1;
}

Dad.prototype.getX = function(){
    return this.x;
}

function Child(){
    Dad.call(this);     
    //这里我们让this指向父类的一个对象,然后返回,可以继承父类私有属性
    this.y = 2;
}
//错误示范:
//Child.prototype = Dad.prototype;
//原因:这样写的话,父类也可以访问,也就是说,子类会影响父类

Child.prototype = Object.create(Dad.prototype); 
//这样做可以让子类不影响父类
//因为通过Object.create复制一次Dad.prototype给Child.prototype,这样可以使这两个互相独立,不会相互影响

Child.prototype.constructor = Child;    //修改constructor指向
var c = new Child();
console.log(c.x);
console.log(c.getX());

ES6中的继承

这种继承方法让我这种学JAVA的倍感亲切,关键点是:
super(); 类似于call继承,继承私有属性
extends 类似于原型对象 继承公有属性
例子如下:

class Dad(){
    constructor(){
        this.x = 1;
    }
    getX(){
        return this.x;
    }
}

class Child extends Dad{
     constructor(){
        super();
        this.y = 2;
    }
    getY(){
        return this.y;
    }
}

var c1 = new Child();
alert(c1.x);
alert(c1.getX());
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值