Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Namespaces with ECMAScript 6 classes

I'm trying to define a class inside the namespace TEST using ECMAScript 6. With "old" Javascript I did this

var TEST=TEST || {};
TEST.Test1 = function() {
}

now I'm trying the following

var TEST=TEST || {};
class TEST.Test2 {

}

but I get an error over the dot between TEST and Test2

Uncaught SyntaxError: Unexpected token

What's the correct way to do what I'm trying to accomplish, without using transpilers but only with native browser javascript?

like image 477
cdarwin Avatar asked Jan 18 '17 16:01

cdarwin


People also ask

Are there namespaces in JavaScript?

JavaScript does not provide namespace by default. However, we can replicate this functionality by making a global object which can contain all functions and variables.

Does TypeScript have namespaces?

In TypeScript, you can use namespaces to organize your code. Previously known as internal modules, namespaces in TypeScript are based on an early draft of the ECMAScript modules.

What are difference between classes and namespaces in phaser?

Classes are data types. They are an expanded concept of structures, they can contain data members, but they can also contain functions as members whereas a namespace is simply an abstract way of grouping items together. A namespace cannot be created as an object; think of it more as a naming convention.


2 Answers

Just as for functions, there are class declarations and class expressions. You can use a class expression instead and assign the result to TEST.Test1:

TEST.Test1 = class { // or `TEST.Test1 = class Test1 {`

};
like image 145
Felix Kling Avatar answered Oct 17 '22 23:10

Felix Kling


Generally this is exactly what ES6 modules are for:

export class Test2 { ... }

...

import * as TEST from './test';

new TEST.Test2(...)

For a single file with class definitions, it can be

const TEST = window.TEST || {};

{
  class Test2 { ... }
  ...

  Object.assign(TEST, { Test2, ... });
}

Another option is using class expressions (as another answer already explained).

like image 38
Estus Flask Avatar answered Oct 17 '22 22:10

Estus Flask