简体   繁体   中英

How to make a class in ecma6 within an encapsulation?

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM