嵌套ES6类? [英] Nested ES6 classes?

查看:1139
本文介绍了嵌套ES6类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎可以在一个构造函数中嵌套一个类,然后可以从类中的任何位置实例化,这个官方是否可以?

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屋!

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