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?
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.
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.
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.
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 {`
};
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With