嵌套ES6类? [英] Nested ES6 classes?
问题描述
似乎可以在一个构造函数中嵌套一个类,然后可以从类中的任何位置实例化,这个官方是否可以?
It seems possible to nest a class in a constructor which can then be instantiated from anywhere within the class, is this official?
例如, p>
E.g.,
class C {
constructor() {
class D {
constructor() { }
}
}
method() {
var a = new D(); // works fine
}
}
//var a = new D(); // fails in outer scope
traceur生成的JS https://google.github.io/traceur-compiler/demo/repl.html
The traceur generated JS https://google.github.io/traceur-compiler/demo/repl.html
$traceurRuntime.ModuleStore.getAnonymousModule(function() {
"use strict";
var C = function C() {
var D = function D() {};
($traceurRuntime.createClass)(D, {}, {});
};
($traceurRuntime.createClass)(C, {method: function() {
var a = new D();
}}, {});
return {};
});
//# sourceURL=traceured.js
推荐答案
不,ES6中没有嵌套的类,如果你的意思是这样的话,那么在类语法中就没有这样的私人成员了。
No, there are no nested classes in ES6, and there is no such thing as private members in the class syntax anyway if you mean that.
当然可以把第二类作为另一个类的静态属性,如下所示:
Of course you can put a second class as a static property on another class, like this:
class A {
…
}
A.B = class {
…
};
或您使用额外的范围:
var C;
{
class D {
constructor() { }
}
C = class C {
constructor() { }
method() {
var a = new D(); // works fine
}
}
}
(似乎有一个bug跟踪,因为它使用一个悬挂的 var
作为类声明而不是块范围)
(There seems to be a bug with traceur as it uses a hoisted var
for the class declaration instead of block scope)
使用提出的类字段语法,也可以编写单个表达式或声明:
With the proposed class field syntax, it will also be possible to write a single expression or declaration:
class A {
…
static B = class {
…
}
};
这篇关于嵌套ES6类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!