クラスの継承

2733 ワード

es 5類の継承
function Animal(name){
            this.name = name;
            this.thirsty = 100;
            this.food = [];
        }
        Animal.prototype.drink = function(){
            return this.thirsty -= 10;
        }
        Animal.prototype.eat = function(item){
            this.food.push(item)
        }
        function Dog(name,breed){
            Animal.call(this,name);
            this.breed = breed;
        }
        
        //Dog.prototype = Animal.prototype
        // Dog.prototype = Animal.prototype    Animal              
        // 1.Dog    constructor  Animal   ,      Dog   
        //     
        //Dog.prototype.constructor = Dog;//   Dog.prototype   Anima.prototype          。  Animal           Dog

        //       
        Dog.prototype = Object.create(Animal.prototype);//Dog.prototype        ,         Animal.prototype 
        Dog.prototype.constructor = Dog;//     Dog.prototype.constructor = Dog            ,    

        Dog.prototype.bark = function(){
            console.log('     ');
        }
        let wangcai = new Dog('wangcai','   ');

es 6クラスの継承
        // es6    
        class Animal {
            constructor(name){
                this.name = name;
                this.thirsty = 100;
                this.food = [];
            }
            drink(){
                return this.thirsty -= 10;
            }
            eat(item){
                this.food.push(item);
            }
            static info(){
                console.log('        ');
            }
        }
        class Dog extends Animal{
            constructor(name,breed){
                super(name);
                this.breed = breed;
            }
            bark(){
                console.log('   ');
            }
        }
        let wangcai = new Dog('wangcai','   ');

        //                       
        Animal.info();
        Dog.info();
        // wangcai.info();             
es 6クラスは内蔵の構造関数を継承します.
//          
        class MoviesList extends Array{
            constructor(name,...movies){
                super(...movies);
                this.name = name;
            }
            add(item){
                this.push(item);
            }
            topStar(limit){
                return this.sort((a,b)=>{return a.star > b.star ? -1 : 1}).slice(0,limit);
            }

        }
        let myLove = new MoviesList('       ',
            {name : '    ',star : 9.5},
            {name : '   ',star : 8.9},
            {name : '      ',star : 9.6},
            {name : '      ',star : 9.3}
        )