最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Namespaces with ECMAScript 6 classes - Stack Overflow

programmeradmin1浏览0评论

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 badges
Add a comment  | 

2 Answers 2

Reset to default 14

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).

发布评论

评论列表(0)

  1. 暂无评论