use*_*531 50 javascript ecmascript-6 traceur
似乎可以在构造函数中嵌套一个类,然后可以从类中的任何地方实例化,这是官方的吗?
[编辑]例如,
class C {
constructor() {
class D {
constructor() { }
}
}
method() {
var a = new D(); // works fine
}
}
//var a = new D(); // fails in outer scope
Run Code Online (Sandbox Code Playgroud)
traceur生成了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
Run Code Online (Sandbox Code Playgroud)
Ber*_*rgi 54
不,ES6中没有嵌套类,如果你的意思是,类语法中没有私有成员.
当然,您可以将第二个类作为静态属性放在另一个类上,如下所示:
class A {
…
}
A.B = class {
…
};
Run Code Online (Sandbox Code Playgroud)
或者你使用额外的范围:
var C;
{
class D {
constructor() { }
}
C = class C {
constructor() { }
method() {
var a = new D(); // works fine
}
}
}
Run Code Online (Sandbox Code Playgroud)
(traceur似乎有一个错误,因为它使用了var类声明而不是块范围的提升)
使用建议的类字段语法,还可以编写单个表达式或声明:
class A {
…
static B = class {
…
}
};
Run Code Online (Sandbox Code Playgroud)
小智 10
类似的东西?
class A {
constructor () {
this.B = class {
echo () {
console.log('I am B class');
}
}
}
echo () {
this.b = new this.B;
this.b.echo();
}
}
var a = new A;
a.echo();Run Code Online (Sandbox Code Playgroud)
您可以使用吸气剂:
class Huffman {
constructor() { /* ... */ }
static get Node() {
return class Node {
constructor() {
var API = this;
API.symbol = 0; API.weight = 0;
return API;
}
};
}
get Node() {
return Huffman.Node;
}
encode() { /* ... */ }
decode() { /* ... */ }
/* ... */
}
// usage
huffman = new Huffman;
new huffman.Node;
new Huffman.Node;
Run Code Online (Sandbox Code Playgroud)
Apple 10.10.2 上最新的 Chrome Dev 44.0.2376.0 在控制台中给出
new huffman.NodeNode {symbol: 0, weight: 0} new Huffman.NodeNode {symbol: 0, weight: 0}在其他新闻中,getter 是让你在 ES6 中做一大堆很酷的事情的秘密武器。
请注意,上述结构中断instanceof了Node(为什么?因为一个全新的类与每个get调用定义)。为了不在instanceof单个 getter 的范围之外中断定义 Node,或者在构造函数中(禁用 Huffman.Node 类属性并导致instanceof在单个 Huffman 实例的命名空间内工作,并在该名称空间之外中断),或者在一个Huffman 的兄弟或祖先作用域(允许instanceof在定义 Node 的作用域以下的所有作用域中工作)。
| 归档时间: |
|
| 查看次数: |
35648 次 |
| 最近记录: |