デザインパターン
シングルトン
与えられたタスクに1つだけオブジェクトが必要な場合、オブジェクトリテラルとしてではなく、class
。柔軟性が重要な場合(テストなど)を除き、明示的にインスタンス化を制限することをお勧めします。
// bad
const MyThing = {
prop1: 'hello',
method1: () => {}
};
export default MyThing;
// good
class MyThing {
constructor() {
this.prop1 = 'hello';
}
method1() {}
}
export default new MyThing();
// best
export default class MyThing {
constructor() {
if (!MyThing.prototype.singleton) {
this.init();
MyThing.prototype.singleton = this;
}
return MyThing.prototype.singleton;
}
init() {
this.prop1 = 'hello';
}
method1() {}
}
JSクラスでのDOM操作
DOM 保証を操作する必要があるクラスを書くとき、コンテナ・オプションが提供されます。 これは、そのクラスが同じページ内で複数回インスタンス化される必要がある場合に便利です。
悪い:
class Foo {
constructor() {
document.querySelector('.bar');
}
}
new Foo();
よかったです:
class Foo {
constructor(opts) {
document.querySelector(`${opts.container} .bar`);
}
}
new Foo({ container: '.my-element' });
このクラスで上記の例をご覧いただけます;