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

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

问题描述

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

It seems possible to nest a class in a constructor which can then be instantiated from anywhere within the class, is this official?

例如,

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 {
    …
};

或者您使用额外的范围:

or you use an extra scope:

var C;
{
    class D {
        constructor() { }
    }
    C = class C {
        constructor() { }
        method() {
            var a = new D();  // works fine
        }
    }
}

(traceur 似乎有一个错误,因为它使用提升的 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天全站免登陆