是否可以从 JavaScript 中的 ECMAScript 6 类继承旧式类? [英] Is it possible to inherit old-style class from ECMAScript 6 class in JavaScript?
问题描述
在 Node.js 4.2.1 上运行以下代码时:
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();
我收到以下错误:
constructor(name) {
^
TypeError: Class constructors cannot be invoked without 'new'
我想知道是否有可能从 ECMAScript 6 类继承旧式 JavaScript类"?而且,如果可能的话,怎么做?
I wonder if it is at all possible to inherit old-style JavaScript "classes" from ECMAScript 6 classes? And, if possible, then how?
推荐答案
一旦您选择了 class
语法,就没有真正的出路.
There's not really a way out once you've opted in to class
syntax.
问题在于 ES6 中的继承是通过使用 super()
的返回值延迟初始化 this
关键字来完成的,这是一个类似于 super()
的构造函数调用代码>新代码>.应用"的旧习语(.call()
) 当前未初始化"子实例上的父构造函数不再工作.
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;
}
当您使用 new MyClass
执行此操作时,您将无法正确设置原型.为此,您需要使用新的 ES6 Reflect.construct
函数,它将子类作为可选的第三个参数:
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;
}
这有一个额外的好处,即 MyDerived
不再需要用 new
调用(只要你提供 MyDerived
new.target
为空).
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屋!