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();

 

你可能感兴趣的:(web前端学习,javascript学习,工作学习总结)