是否可以在JavaScript中从ECMAScript 6类继承旧式类? [英] Is it possible to inherit old-style class from ECMAScript 6 class in JavaScript?

查看:130
本文介绍了是否可以在JavaScript中从ECMAScript 6类继承旧式类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



 'use strict'; var util = require('util' ); class MyClass {constructor(name){this.name = name; }} function MyDerived(){MyClass.call(this,'MyDerived');} util.inherits(MyDerived,MyClass); var d = new MyDerived();  



我收到以下错误:

 构造函数(name){
^

TypeError:类构造函数不能在没有'new'的情况下被调用

我想知道是否可以从ECMAScript 6类继承旧式JavaScript类?而且,如果可能,那么如何?

解决方案

一旦你选择了 class 语法



问题是ES6中的继承是通过晚期初始化 code>关键字,返回值来自 super(),这是一个类似于 new 的构造函数调用。旧的应用成语( .call() )当前未初始化子实例的父构造函数不再工作



您仍然可以使用寄生继承 - 您必须明确构造实例,扩展它,并且返回

  function MyDerived(){
var derived = new MyClass('MyDerived');
... //设置属性
return derived;
}

当您使用新建MyClass ,你不会正确设置原型。为此,您将需要使用新的ES6 Reflect.construct 函数,将子类作为可选的第三个参数:

 函数MyDerived(){
var derived = Reflect.construct(MyClass,['MyDerived'],new.target || MyDerived);
... //设置属性
return derived;
}

这有额外的好处, MyDerived 不需要再调用 new (只要您提供 MyDerived code> new.target 为空)。


When running the following code on Node.js 4.2.1:

'use strict';

var util = require('util');

class MyClass {
  constructor(name) {
    this.name = name;
  }
}

function MyDerived() {
  MyClass.call(this, 'MyDerived');
}

util.inherits(MyDerived, MyClass);

var d = new MyDerived();

I get the following error:

constructor(name) {
         ^

TypeError: Class constructors cannot be invoked without 'new'

I wonder if it is at all possible to inherit old-style JavaScript "classes" from ECMAScript 6 classes? And, if possible, then how?

解决方案

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).

这篇关于是否可以在JavaScript中从ECMAScript 6类继承旧式类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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