Static Class Methods in JavaScript
One part of JavaScript that flew by me last year was that static methods for classes finally have wide browser support. This makes the syntax for methods called on a class object itself instead of instantiated version of it much more obvious. Here is what it looked like before:
class Money { constructor(value) { this.baseValue = value; } toString() { const rounded = Math.round(this.baseValue * 100) / 100; // For example purposes, no internationalization is done return `$${rounded}`; } // This value will be used in any calculation valueOf() { return this.baseValue; } } // Static method Money.subtract = function subtract(money1, money2) { return new Money(money1 - money2); }; const revenue = new Money(2145.2267); const costs = new Money(1000); console.log(`Revenue: ${revenue}`); // $2145.23 console.log(`Costs: ${costs}`); // $1000 console.log(`Profit: ${Money.subtract(revenue, costs)}`); // Profit: $1145.23
Note how valueOf makes the calculations easier. If you are unfamiliar with that, you can checkout my post on that. Anyways, with the static keyword, that can now be moved directly into the class:
class Money { constructor(value) { this.baseValue = value; } toString() { const rounded = Math.round(this.baseValue * 100) / 100; // For example purposes, no internationalization is done return `$${rounded}`; } // This value will be used in any calculation valueOf() { return this.baseValue; } static subtract(money1, money2) { return new Money(money1 - money2); } }
Github Location https://github.com/Jacob-Friesen/obscurejs/blob/master/2019/classStatic.js







