ES6 class 类

ES6 class 类

    class Animal{
        constructor(props){
            this.name = props.name || '未知'

        };
        eat(){
            alert(this.name + ' 在吃东西')
        }
        play(){
            alert(this.name + ' 在踢球')
        }

    }   
    class Bird extends Animal{
        constructor(props){
            //this.type = props.type || '未知'  //报错 使用this必须在调用super之后,才会创建this
            super(props)
            //super关键字, 它在这里表示父类的构造函数, 用来新建父类的this对象。
            //子类必须在constructor方法中调用super方法, 否则新建实例时会报错。 这是因为子类没有自己的this对象, 而是继承父类的this对象, 然后对其进行加工。 如果不调用super方法, 子类就得不到this对象。
            // 另一个需要注意的地方是, 在子类的构造函数中, 只有调用super之后, 才可以使用this关键字, 否则会报错。 这是因为子类实例的构建, 是基于对父类实例加工, 只有super方法才能返回父类实例。
            this.type = props.type || '未知'
        }
        fly(){
            alert(this.name + ' 在飞……')
            super.play()
            //  调用父类的 play()  
        }

    }
    var obj ={
        name:'胡德',
        type:'麻雀'
    }
    function text(){
        var sparrow = new Bird(obj)
        debugger
        sparrow.eat()
        sparrow.fly()
    }
    window.onload = text;

猜你喜欢

转载自blog.csdn.net/weixin_36934930/article/details/81060145