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?
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?
Share Improve this question asked Jan 18, 2017 at 16:05 cdarwincdarwin 4,29110 gold badges47 silver badges70 bronze badges2 Answers
Reset to default 14Just 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).