javaScript的继承方式

1.原型继承

特点:将父类的私有+公有作为子类的共有

将子类的原型指向父类的实例

给B的prototype属性重新赋值为a这个对象,B的原型就是a这个对象

  //原型模式 将公有的属性加到prorotype上
        Student.prototype.introduce = function(){
            console.log("我叫" + this.name + "我今年" + this.age + ",我来学习js啦");
        }
        var stu1 = new Student("张三",13);
        var stu2 = new Student("李四",13);

        stu1.introduce();
        stu2.introduce();

        console.log(stu1.introduce == stu2.introduce);//true

2.call继承

特点:将父类的私有作为子类的私有

        //call继承
        //父类  
        function A(x,y){
            this.x = x;
            this.y = y;
        }
        //公有的
        A.prototype.getX = function(){
            console.log(this.x);
        }

        A.prototype.getY = function(){
            console.log(this.y);
        }

        //子类
        function B(x,y,z){
            //增加公有属性
            this.z = z;
            A.call(this,x,y);
        }
        var b = new B(100,20,30);
        console.log(b);//B {z: 30, x: 100, y: 20}

冒充对象继承

特点:将父类的私有+公有 作为子类的私有

        //父类
        function A(x,y){
            this.x = x;
            this.y = y;
        }
        //公有的
        A.prototype.getX = function(){
            console.log(this.x);
        }
        A.prototype.getY = function(){
            console.log(this.y);
        }
        //子类
        function B(z,x,y){
            //增加私有属性
            this.z = z;
            //创建A这个类的实例
            var a = new A(x,y);
            //迭代a这个对象
            for(var key in a){
                //将迭代的属性和值给到a
                this[key] = a[key];
            }
        }
        var b = new B(100,20,30);
        console.log(b);//B {z: 100, x: 20, y: 30, getX: ƒ, getY: ƒ}

寄生组合继承

特点:将父类的私有作为子类的私有,将父类的公有作为子类的公有

//寄生组合继承
        //父类
        function A(x,y){
            this.x = x;
            this.y = y;
        }
        //共有的
        A.prototype.getX = function(){
            console.log(this.x);
        }
        A.prototype.getY = function(){
            console.log(this.y);
        }
        //子类
        function B(z){
            //增加私有属性
            this.z = z;
            A.call(this,10,20);
        }
        //将子类的原型指向父类的原型
        B.prototype = A.prototype;
        var b= new B(100);
        console.log(b);

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值