ES6 javascript静态类继承:覆盖超类使用的静态方法的子类

时间:2016-06-08 16:06:37

标签: javascript class inheritance ecmascript-6 method-overriding

如何覆盖子类中的静态方法,并让超类方法仍然使用它们? 这是代码示例:

    class SuperClass {
      static calc1() {
        return 5;
      }

      static calc2() {
        return 10;
      }

      static calcAll() {
        //here must be something else, instead of SuperClass reference
        return SuperClass.calc1() + SuperClass.calc2();
      }
    }


    class SubClass extends SuperClass {
      //override
      static calc1() {
        return 1000;
      }
    }

    console.log(SuperClass.calcAll()); //expected 5+10 = 15, got 15
    console.log(SubClass.calcAll()); //expected 1000+10 = 1010, got 15

1 个答案:

答案 0 :(得分:0)

解决方案

刚刚找到解决方案,请使用this
但不确定这是否正确,所以请在必要时进行审核/纠正。

class SuperClass {
  static calc1() {
    return 5;
  }

  static calc2() {
    return 10;
  }

  static calcAll() {
    //reference to this, bound to class itself, because of 'static'
    return this.calc1() + this.calc2();
  }
}


class SubClass extends SuperClass {
  //override
  static calc1() {
    return 1000;
  }
}

console.log(SuperClass.calcAll()); //5+10 = 15
console.log(SubClass.calcAll()); //1000+10 = 1010

可选信息:

我顺便找到的一些东西

覆盖实例方法,是相同的:

class SuperClass {
  calc1() {
    return 5;
  }

  calc2() {
    return 10;
  }

  calcAll() {
    //reference to this, bound to instance
    return this.calc1() + this.calc2();
  }
}


class SubClass extends SuperClass {
  //override
  calc1() {
    return 1000;
  }
}

console.log(new SuperClass().calcAll()); //5+10 = 15
console.log(new SubClass().calcAll()); //1000+10 = 1010

要在实例方法中使用静态方法,或者在实例方法上映射静态方法,请使用当前构造函数引用。

class SuperClass {
  static calc1() {
    return 5;
  }

  calc2() {
    return 10;
  }

  calcAll() {
    //'this' bound to instance, and we get current! (e.g. SubClass) class, by .constructor call
    return this.constructor.calc1() + this.calc2();
  }
}


class SubClass extends SuperClass {
  //override
  static calc1() {
    return 1000;
  }
}

console.log(new SuperClass().calcAll()); //5+10 = 15
console.log(new SubClass().calcAll()); //1000+10 = 1010

将静态方法映射到实例方法:

class SuperClass {
  static calc1(num) {
    return num;
  }

  calc1(...args) {
    //reference to static
    return this.constructor.calc1.apply(this.constructor, args);
  }
 /* alternative:
  calc1(num) {
    //reference to static
    return this.constructor.calc1(num);
  }
  */

}


class SubClass extends SuperClass {
  //override
  static calc1(num) {
    return num + 1000;
  }
}

//call statics
console.log(SuperClass.calc1(5)); //5
console.log(SubClass.calc1(5)); //5+1000 = 1005
//call instance
console.log(new SuperClass().calc1(5)); //5
console.log(new SubClass().calc1(5)); //5+1000 = 1005