Is it possible to inherit old-style class from ECMAScript 6 class in JavaScript?

后端 未结 1 2041
清酒与你
清酒与你 2020-12-11 04:34

When running the following code on Node.js 4.2.1:



        
相关标签:
1条回答
  • 2020-12-11 05:02

    There's not really a way out once you've opted in to class syntax.

    The problem is that inheritance in ES6 is done by late-initialising the this keyword with the return value from super(), which is a constructor call like with new. The old idiom of "applying" (.call()) the parent constructor on the currently "uninitialised" child instance does work no more.

    What you can still do is to resort to "parasitic inheritance" - you'll have to explicitly construct the instance, extend it, and return it:

    function MyDerived() {
      var derived = new MyClass('MyDerived');
      … // set up properties
      return derived;
    }
    

    When you do this with new MyClass, you won't get the prototype set up correctly however. For that, you will need to use the new ES6 Reflect.construct function, which takes the child class as an optional third parameter:

    function MyDerived() {
      var derived = Reflect.construct(MyClass, ['MyDerived'], new.target||MyDerived);
      … // set up properties
      return derived;
    }
    

    This has the additional benefit that MyDerived doesn't need to be called with new any more (as long as you supply MyDerived when new.target is empty).

    0 讨论(0)
提交回复
热议问题