继承

一.es6的继承

 class Peopel{
                constructor(name,age){
                     this.name = name
                     this.age = age
                }
                eat(){}
                speak(){}
            }
            console.log( new Peopel() )

            class ChenesePeople extends Peopel{
                constructor(name,age,id){
                     super(name,age)
                     this.id = id
                }
            }
            class PayBool{
                 pay(){}
            }

            class Student extends ChenesePeople{
                    constructor(name,age,id){
                         super(name,age,id)
                    }
            }
            console.log( new Student() )

二.es5的继承

1. 构造函数实现继承(注意:使用此方法无法继承到原型上的属性方法)
 // 构造函数实现继承
         function AA(name,age ){
              this.name = name;
                this.age = age;
                this.fun = function(){
                }
         }
         AA.prototype.say=function(){}
         function BB(){
             this
            //让AA里的this指向BB  New出来的实例
              AA.call(this)
         }
         
        console.log( new AA() )
        console.log( new BB() )
2. 原型链继承(因为两个·的原型指向同一个,所以任意一个改变了都会改变原型上的东西)
function AA(name,age ){
              this.name = name;
                this.age = age;
                this.color= ["red","yellow"]
                this.fun = function(){
                }
         }
         AA.prototype.say=function(){}
         function BB(){
         }
         BB.prototype = new AA()
         
        // console.log( new AA() )
        console.log( new BB() )
        let b = new BB()
        let b1 = new BB()

        b.color.push("black")

        console.log( b1.color )
3.组合方式继承
function AA(name,age){
            this.name = name;
            this.age = age;
            this.fun = function(){}
        }
        AA.prototype.say=function(){}

        function BB () {  
             AA.call(this)
        }
        BB.prototype = AA.prototype1
        BB.prototype.constructor = BB
        console.log(new BB())

    console.log(Object.create({}))  
    console.log({})

你可能感兴趣的:(继承)