默认导出类的新实例

时间:2019-07-16 04:15:34

标签: javascript es6-modules

下面的代码片段每次导入都会产生新的实例吗?

// 1st implementation

class ConnectionManager {
...
}

export default new ConnectionManager();
// 2nd implementation

class ConnectionManager {
...
}

const connectionManager = new ConnectionManager();
export default connectionManager;

如果是,如何在每次导入中获得相同的实例?

3 个答案:

答案 0 :(得分:0)

在创建JavaScript模块以从模块中导出函数,对象或原始值时,将使用export语句,以便其他程序可以通过import语句使用它们。

有两种不同的导出类型,命名导出和默认导出。每个模块可以有多个命名导出,但是只有一个默认导出。

export default class ConnectionManager { .. }

class ConnectionManager {
   ...
}
export default connectionManager;

答案 1 :(得分:0)

ES6模块遵循单实例模式。也就是说,实例是在模块加载时创建的。

Here是关于它的文章。

// File: yolo.js

class Yolo {}
export let yolo = new Yolo();

// File: laser.js

import { yolo } from "./yolo.js";
// yolo is a single instance of Yolo class


// File: cat.js

import { yolo } from "./yolo.js";
// same yolo as in laster.js

答案 2 :(得分:0)

应该相同。

以下示例使用这两种实现,将它们导入2个不同的文件,并将它们全部导入单个index文件。每次创建实例时,我们都会为该类生成一个随机的value,并记录其创建。

// ConnectionManagerImpl1.ts
class ConnectionManagerImpl1 {
    public value;

    constructor() {
        this.value = Math.random().toString(36).substring(7);
        console.log(`New ConnectionManagerImpl1 instance created: ${this.value}`)
    }
}

export default new ConnectionManagerImpl1();

// ConnectionManagerImpl2.ts
class ConnectionManagerImpl2 {
    public value;

    constructor() {
        this.value = Math.random().toString(36).substring(7);
        console.log(`New ConnectionManagerImpl2 instance created: ${this.value}`)
    }
}

const connectionManagerImpl2 = new ConnectionManagerImpl2();
export default connectionManagerImpl2;

// import1.ts
import connectionManagerImpl1 from './ConnectionManagerImpl1';
import connectionManagerImpl2 from './ConnectionManagerImpl2';

export { connectionManagerImpl1, connectionManagerImpl2 };

// import2.ts
import connectionManagerImpl1 from './ConnectionManagerImpl1';
import connectionManagerImpl2 from './ConnectionManagerImpl2';

export { connectionManagerImpl1, connectionManagerImpl2 };

// index.ts
import * as import1 from './import1';
import * as import2 from './import2';

console.log(import1)
console.log(import2)
console.log("Done")

使用tsc --module 'commonjs' * && node index.js

运行上述设置

输出:

New ConnectionManagerImpl1 instance created: ddt3re
New ConnectionManagerImpl2 instance created: uv5z6
{ connectionManagerImpl1: ConnectionManagerImpl1 { value: 'ddt3re' },
  connectionManagerImpl2: ConnectionManagerImpl2 { value: 'uv5z6' } }
{ connectionManagerImpl1: ConnectionManagerImpl1 { value: 'ddt3re' },
  connectionManagerImpl2: ConnectionManagerImpl2 { value: 'uv5z6' } }
Done

如您所见,仅创建了ConnectionManagerImpl1ConnectionManagerImpl2的1个实例。因此,两个实现都应该只创建一个实例。