Take this example of an ES6 class for a website header:
// ./Header.js
export default class Header {
constructor() {
console.log('Header is constructing');
this.root = document.querySelector('header');
this.show = this.show.bind(this);
this.hide = this.hide.bind(this);
// Other stuff
}
// Other methods for account and interactive menus
hide() {
this.root.classList.add('hide');
}
show() {
this.root.classList.add('show');
}
}
Then take for example, other classes that would invoke methods from the header:
// ./Search.js
import 'Header';
export default class Search {
constructor() {
this.header = new Header();
// Other stuff
}
// Other methods
invoke() {
this.header.hide();
}
cancel() {
this.header.show();
}
}
// ./ScrollToTop.js
import 'Header';
export default class ScrollToTop {
constructor() {
this.root = document.querySelector('#scrollToTop');
this.header = new Header();
this.onClick = this.onClick.bind(this);
this.root.addEventListener('click', this.onClick);
// Other stuff
}
// Other methods
onClick() {
window.scrollTo({top: 0});
this.header.show();
}
}
The header is constructed each time you use new Header
. Given that we would like the Header to be both an object and an exportable: how would one design the code to make the Header only constructed once?