JS-继承的实现方式

原型继承

通过prototype把子类的原型绑到父类的实例上,子类就可以调用父类的公有属性和方法、私有的属性和方法。但是这种方式实现继承,无论父类中公有的属性和方法还是私有的属性和方法,都会变成子类公有的属性和方法,这样子类就可以重写父类的属性和方法,也有影响父类的其他实例。

function Parent(x){
	this.x = x;
};
Parent.prototype.getX=function(){
	console.log(x)
};
function Child(y){
	this.y = y;
};
Child.prototype = new Parent(100);
Child.prototype.constructor = Child;
Child.prototype.getY=function(){
	console.log(y)
};
let child = new Child(200);
child.getX();
child.getY();

在这里插入图片描述

call继承

通过call改变this指向问题,把父类公有的属性和方法当作函数来执行,但是不可以使用父类的私有属性和方法。

function parent(x) {
            this.x = x;
        }
        parent.prototype.getX = function () {
            console.log(this.x);
        }

        function children(y) {
            parent.call(this, 200);
            this.y = y
        }
        children.prototype.getY = function () {
            console.log(this.y);
            console.log(this.x)
        }
        let child = new children(100);
        child.getY();

在这里插入图片描述

寄生组合继承

这个就好多了,其实就是call+类似原型继承,父类公有的属性和方法也会成为子类公有的属性和方法,父类私有的属性和方法也会成为子类私有的属性和方法。very good!

 function parent(x) {
            this.x = x;
        }
        parent.prototype.getX = function () {
            console.log(this.x);
        }
        child.prototype = Object.create(parent.prototype);
        child.prototype.constructor = child;

        function child(y) {
            parent.call(this, 100);
            this.y = y;
        }
        child.prototype.getY = function () {
            console.log(this.y);
        }
        let kid = new child(200);
        kid.getX();
        kid.getY();

es6中class

非常如此之方便的class来了,也是父类的公有和私有对应是子类的公有和私有的属性和方法

 class parent {
            constructor(x) {
                this.x = x;
            }
            getX = function () {
                console.log(this.x);

            }
        }
        class child extends parent {
            constructor(y) {
                super(100);
                this.y = y;
            }
            getY = function () {
                console.log(this.y);

            }
        }
        let ch = new child(200)
        ch.getX()
        ch.getY()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值