0

In ecma6 javascript, how can I make a class that is only defined in a scope of something like:

var name_space = new function() {

    class ball {
      ....
    }

    var handball = new ball();  // real object

};

var handball = new ball(); // error, ball not defined

is this possible?

Thanks

omega
  • 40,311
  • 81
  • 251
  • 474

2 Answers2

3

Sure:

(() => {
  class Ball {

  }

  let handball = new Ball(); // works
})();

let handball = new Ball(); // ReferenceError

You probably don't want to do this, though. ES6 modules are a pleasant alternative to the IIFE pattern.

  • Are you saying that in es6, having global namespaces doesn't work if you do import? – omega Jan 17 '17 at 22:21
  • 1
    Basically, yeah. Each module has its own scope, which doesn't pollute the global namespace. You can selectively `export` things from your modules and then pull in only the things you need with `import`. It's the same thing immediately-invoked functions were used to accomplish, just without the clunky syntax. –  Jan 17 '17 at 22:53
  • but if file imports like this `import foo from A', and foo is a function that alerts 1, is it the same thing as var foo = function() {alert(1)}; instead of doing the import? So foo is not in the window variable. – omega Jan 18 '17 at 00:38
  • I may be misunderstanding your question, so sorry if this isn't what you're getting at but: When you use import and export, each file is a module and each module has its own scope. So when you import `foo` from `A`, it's only available in that file and doesn't get attached to `window` or leak into any other scope. Under the hood, most module bundlers (like Browserify or Webpack) will use functions to wrap everything up and make the code work in a web browser where modules aren't currently supported. Which is a long way to say yeah, foo is not in the window variable. Hope that helps! –  Jan 18 '17 at 01:32
2

Classes already are defined only in the nearest block scope:

{ // a block scope
    class Ball {
        …
    }
    let handball = new Ball();  // real object
}

var handball = new Ball(); // ReferenceError, Ball not defined
Bergi
  • 630,263
  • 148
  • 957
  • 1,375