web前端——JS中的继承方式

ES5

//ES5中的写法一

    function Phone(color){
        this.color = color;
        this.show = function(){
            console.log("你喜欢看的颜色是:"+this.color);
        }
    }
    function Vivo(color){
        Phone.call(this,color);
    }
    var vivo = new Vivo("黄色");
    vivo.show();

//这里主要利用了call()方法改变this指向
    写法二,原型链继承

    function Person(name,age){
        this.name = name;
        this.age = age;
        this.eat = function(){
            console.log(name + "很能吃");
        }
    }

    function Player(type){
        this.type = type;
    }
    Player.prototype = new Person("简自豪");
    var player = new Player();
    player.eat();

    //写法三,拷贝继承
    function MingXing(name){
        this.name = name;
        this.sing = function(){
            console.log(this.name + "会唱歌");
        }
    }
    var jack = {
        extend:function(obj){
            for(var val in obj){
                this[val] = obj[val];
            }
        }
    };
    jack.extend(new MingXing("陈明"));
    jack.sing();

    //写法四,组合继承
    function Car(color){
        this.color = color;
    }

    function Passat(color,type){
        Car.call(this,color);
        this.type = type;
    }
    Passat.prototype = new Car();
    Passat.prototype.run = function(){
        console.log(this.color+this.type+"会跑");
    }
    var passat = new Passat("黑色","帕撒特");
    passat.run();

ES6

class Fu{
        constructor(x,y){
            this.x = x;
            this.y = y;
        }
        show(){
            console.log("x = "+this.x+",y = "+this.y);
        }
    }
    class Zi extends Fu{
        constructor(x,y){
            super(x,y);
        }
    }
    const zi = new Zi(1,2);
    zi.show();

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值