我发现您的问题有些混乱,所以让我澄清一下。
在 ES6 中,您可能知道当需要导出模块时有两种策略。您可以使用默认导出 or 多次出口。让我们举一个非常基本的例子(一个简单的记录器console
):
function info(msg) {
console.info(`[Info] ${msg}`);
}
function error(msg) {
console.error(`[Error] ${msg)`);
}
默认导出
在这里我们必须对我们的功能进行分组。在 JavaScript 中执行此操作的最惯用方法是使用对象文字(请参阅揭示模块模式):
export default {
info(msg) {
console.info(`[Info] ${msg}`);
},
error(msg) {
console.error(`[Error] ${msg}`);
}
};
然后,在我们的客户端代码中,我们将像这样使用这个模块:
import logger from './logger'
logger.info('Hello!');
logger.error('Oops!');
多次出口
这里我们可以独立导出我们的函数:
export function info(msg) {
console.info(`[Info] ${msg}`);
}
export function error(msg) {
console.error(`[Error] ${msg}`);
}
然后,在我们的客户端代码中,我们将像这样使用这个模块:
import {info, error} from './logger'
info('Hello!');
error('Oops!');
Done.
我建议您通过我们的功能示例来了解 ES6 模块系统是如何工作的。这和课堂上的情况是完全一样的......
辛格尔顿?
通过阅读评论,我看到了另一个需要澄清的困惑:辛格尔顿.
Singleton 是一种设计模式,它使得实例化一个类成为可能once。现在想象一下我们的类如下:
export default class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
};
我们可以这样使用它:
import Person from './Person';
let me = new Person('Baptiste', 'Vannesson'),
you = new Person('David', 'Choi');
console.log(Object.is(me, you)); // false, so there are two instances of Person
console.log(me.firstName, me.lastName); // Baptiste Vannesson
console.log(you.firstName, you.lastName); // David Choi
正如你所看到的,Person 和 Singleton 没有任何关系!它将是一个具有以下 Java 启发实现的单例:
export default (() => {
class Person {
// Private constructor
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}
return {
// Public static factory method
getInstance(firstName, lastName) {
if (!Person.instance) {
Person.instance = new Person(firstName, lastName);
}
return Person.instance;
}
};
})();
客户端代码:
import Person from './Person';
let me = Person.getInstance('Baptiste', 'Vannesson'),
you = Person.getInstance('David', 'Choi');
console.log(Object.is(me, you)); // true, so there is only one instance
console.log(me.firstName, me.lastName); // Baptiste Vannesson
console.log(you.firstName, you.lastName); // Baptiste Vannesson (still me!)
为了简单起见,您可能更喜欢直接导出实例:
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
};
export default new Person('David', 'Choi');
客户端代码:
import person from './person';
// Person is not a constructor but a simple instance
let me = person,
you = person;
console.log(Object.is(me, you)); // true
console.log(me.firstName, me.lastName); // David Choi
console.log(you.firstName, you.lastName); // David Choi
如果这样做,使用对象文字会更简单:
export default {
firstName: 'David',
lastName: 'Choi'
};
此处客户端代码不变。