js的繼承

1.構造函數實現繼承

      缺點:不能繼承方法

        //構造函數實現繼承
        function Parent(name){
            this.name = name
        }
        Parent.prototype.showName = function(){
            console.log(this.name)
        }

        function Son(name,age){
            Parent.call(this, name)
            this.age = age
        }

2.藉助原型鏈繼承

   缺點:一修改全部修改

       function Parent(name){
            this.name = name
        }
        Parent.prototype.showName = function(){
            console.log(this.name)
        }

        function Son(age){
            this.age = age;
        }

        Son.prototype = new Parent('張三')

3.組合型繼承

       function Parent(name){
            this.name = name
        }
        Parent.prototype.showName = function(){
            console.log(this.name)
        }
       
        function Son(name,age){
            Parent.call(this,name)
            this.age = age
        }
        Son.prototype = Object.create(Parent.prototype) 
        Son.prototype.constructor =  Son 

4.類的繼承

    class Parent {
            constructor(name) {
                this.name = name
            }
            showName() {
                alert(this.name)
            }
        }
        class Son extends Parent {
            constructor(name) {
                super(name)
                this.type = 'ss'
            }
        }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章