美文网首页
Javascript 面向对象(ES6继承)

Javascript 面向对象(ES6继承)

作者: 龚达耶 | 来源:发表于2019-10-18 20:27 被阅读0次

ES6的继承我们运用了class语法糖这样可以更像我们经典的面向对象语言。

我们用class创造的类其实还是一个构造方法

class ddw{
      constructor(x, y){
        this.x = x;
        this.y = y;
      }
      bart(){
        console.log(this.x+this.y)
      }
    }
    console.log(typeof ddw) // function
    console.log(Ddw.prototype.constructor === Ddw) // true

所有我们定义的方法都会被实例继承

class Ddw{
      constructor(x, y){
        this.x = x;
        this.y = y;
      }
      bart(){
        console.log(this.x+this.y)
      }
    }
    let gongxi = new Ddw(2,3)
    gongxi.bart() //5

但如果我们加了static就不行了

    class Ddw{
      constructor(x, y){
        this.x = x;
        this.y = y;
      }
      static bart(){
        console.log(this.x+this.y)
      }
    }
    let gongxi = new Ddw(2,3)
    gongxi.bart()
image.png
因为加了static表示只能通过类调用而不能通过实例继承

但是父类静态方法可以被子类继承

    class Ddw{
      constructor(x, y){
        this.x = x;
        this.y = y;
      }
      static bart(a, b){
        console.log(a+b)
      }
    }
    class Ddw2 extends Ddw {}
    Ddw2.bart(2,3) // 5

我们也可以用super调用父类

 class Ddw{
      constructor(x, y){
        this.x = x;
        this.y = y;
      }
      static bart(a, b){
        return a+b
      }
    }
    class Ddw2 extends Ddw {
      static bart2(a,b){
        console.log('answer is '+super.bart(a,b))
      }
    }
    Ddw2.bart2(2,3) //answer is 5

在子类中必须加入super()才能使用this,因为子类创建基于父类所以要super才能返回父类实例

是否继承可以用getPrototypeOf()判断

console.log(Object.getPrototypeOf(Ddw2) === Ddw) // true

相关文章

网友评论

      本文标题:Javascript 面向对象(ES6继承)

      本文链接:https://www.haomeiwen.com/subject/bxtbmctx.html