javascriptecmascript-6traceur

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?

[EDIT] E.g.,

class C {

    constructor() {
        class D {
            constructor() { }
        }
    }

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

}

//var a = new D();  // fails in outer scope

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

Solution

  • No, there are no nested class scopes 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
            }
        }
    }
    

    (There seems to be a bug with traceur as it uses a hoisted var for the class declaration instead of block scope)


    With the class field syntax, it will also be possible to write a single expression or declaration:

    class A {
        …
        static B = class {
             …
        }
    };