The module pattern is an effective method for dividing a larger codebase into smaller, reusable components. It encourages code encapsulation by default, keeping values private within a module and preventing them from being altered. Only the values explicitly marked for export with the "export" keyword can be accessed by other parts of the codebase.
Encapsulation: The values within a module are scoped to that specific module. Values that aren't explicitly exported are not available outside of the module.
Reusability: We can reuse modules throughout our application
export function sum(x, y) {
return x + y;
}
export function multiply(x, y) {
return x * y;
}
export function subtract(x, y) {
return x - y;
}
export function divide(x, y) {
return x / y;
}
Concept
The module pattern is an effective method for dividing a larger codebase into smaller, reusable components. It encourages code encapsulation by default, keeping values private within a module and preventing them from being altered. Only the values explicitly marked for export with the "export" keyword can be accessed by other parts of the codebase.
模块模式是将较大的代码文件分割成多个更小、可重用的组件的有效方法。它默认情况下鼓励代码封装,通过将模块内的值保持为私有,防止其被修改。只有使用 "export" 关键字明确标记为导出的值才可以被代码中的其他部分访问。
Tradeoffs
Encapsulation: The values within a module are scoped to that specific module. Values that aren't explicitly exported are not available outside of the module.
Reusability: We can reuse modules throughout our application
Stackblitz
math.js
index.js