在 JavaScript 中
如果使用 ES6
static
函数可以在一个class
如果使用 ES5
经过几天的使用,下面是我想出的,
它是最小的,也有很多方便:
function MathFunctions() {
let thefo = {}; // the functions object
thefo.sum = sum = (a, b) => {
return a + b;
};
thefo.avg = avg = (a, b) => { // name is repeated 2 times - minor inconvenience
return sum(a, b) / 2; // calls sum, another function without using 'this'
};
return thefo; // no need to go down & export here always for each new function - major convenience
}
// Usage
console.log(MathFunctions().sum(1, 2));
console.log(MathFunctions().avg(1, 2));
// OR
const mf = MathFunctions();
console.log(mf.sum(1, 2));
console.log(mf.avg(1, 2));