天天看點

js類的封裝和繼承

//ES6之前沒有class類的定義都是通過構造函數 call實作類的繼承      
function Animal(name, age) {
            this.name = name;
            this.age = age
        }
        Animal.prototype.eat = function() {
            console.log("animal eat")
        }

        function Dog(name, age, sex) {
            Animal.call(this, name, age)

            this.sex = sex
        }
        Dog.prototype = new Animal()
        Dog.prototype.constructor = Dog
        var dog = new Dog("dd", 12, "w")
        console.log(dog)      
//ES6類封裝 constructor中this指向類new執行個體對象 方法中的this指向這個方法的調用者
        class Star {
            constructor(name) {
                this.name = name;
                this.btn = document.querySelector('button');
                this.btn.onclick = this.click
            }
            click() {
                console.log(this, this.name)//此時this是button
            }
            sing(song) {
                console.log(this.name + " sing " + song)
            }
            show(movie) {
                console.log(this.name + " show " + movie)
            }
        }
        var zxy = new Star("張學友")
        var ldh = new Star("劉德華")
        zxy.sing("一千個傷心的理由")
        ldh.sing('冰雨')
            //es6類繼承 
        class Animal {
            constructor(name) {
                this.name = name
            }
            eat() {
                console.log(this.name + ' eat')
            }
        }
        class Dog extends Animal {

        }
        var dog = new Dog('dog')
        dog.eat()

        class Calc {
            constructor(x, y) {
                this.x = x;
                this.y = y
            }
            sum() {
                console.log(this.x + this.y)
            }
        }
        class Add extends Calc {
            constructor(x, y) {
                super(x, y)
            }
            add() {
                console.log(this.x + this.y)
            }
        }
        var add1 = new Add()
        add1.sum()
        add1.add()      

繼續閱讀