在ES6中继承静态方法 [英] Inherit static methods in ES6

查看:145
本文介绍了在ES6中继承静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用ES6语法是否可以扩展一个类并继承其静态方法?如果是这样,我们可以在子类的静态方法中调用super吗?



示例:

 code> class Parent {
static myMethod(msg){
console.log(msg)
}
}

class Child extends Parent {
static myMethod(){
super(hello)
}
}

Child.myMethod(); // logshello

这是给我一个没有方法调用在我的透明器(Reactify)中的未定义错误。



____ SuperProtoOfParent.open.call(this); spec here 和这里 super 基本引用了当前这个对象的原型。在静态方法中,它将引用继承的类。所以要调用父静态方法,你必须调用 super.myMethod('some message')。这是一个例子:

  class Parent {
static myMethod(msg){
console.log 'static',msg);
}

myMethod(msg){
console.log('instance',msg);
}
}

class Child extends Parent {
static myMethod(msg){
super.myMethod(msg);
}

myMethod(msg){
super.myMethod(msg);
}
}

Child.myMethod(1); // static 1
var child = new Child();

child.myMethod(2); //实例2

这是es6fiddle


Using ES6 syntax is it possible to extend a class and inherit its static methods? And if so, can we call super in the subclass's static method?

Example:

class Parent {
  static myMethod(msg) {
    console.log(msg)
  }
}

class Child extends Parent {
  static myMethod() {
    super("hello")
  }
}

Child.myMethod();  // logs "hello" 

This is giving me a no method call on undefined error in my transpiler (Reactify).

____SuperProtoOfParent.open.call(this);

解决方案

According to the spec here and here super base references to the prototype of the current this object. In static methods it will reference to the inherited class . So to invoke the parent static method you must call super.myMethod('some message'). Here is an example:

class Parent {
  static myMethod(msg) {
    console.log('static', msg);
  }

  myMethod(msg) {
    console.log('instance', msg);
  }
}

class Child extends Parent {
  static myMethod(msg) {
    super.myMethod(msg);
  }

  myMethod(msg) {
    super.myMethod(msg);
  }
}

Child.myMethod(1); // static 1
var child = new Child(); 

child.myMethod(2); // instance 2

Here is the es6fiddle

这篇关于在ES6中继承静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆