https://scotch.io/tutorials/better-javascript-with-es6-pt-ii-a-deep-dive-into-classes
review:
Class Constructors
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
"use strict"; // Enforcing constructor call function Food (name, protein, carbs, fat) { // Manually call 'new' if user forgets if (!new.target) return new Food(name, protein, carbs, fat); this.name = name; this.protein = protein; this.carbs = carbs; this.fat = fat; } const fish = Food('Halibut', 26, 0, 2); // Oops -- but, no problem! fish; // 'Food {name: "Halibut", protein: 20, carbs: 5, fat: 0}' |
Static methods
Static methods are methods on the constructor function itself, which are not available on instances of the class.
You define them by using the static keyword.
1 2 3 4 5 6 7 8 9 10 11 12 |
"use strict"; class Food { // Class definition is the same as before . . . // Adding a static method static describe () { console.log('"Food" is a data type for storing macronutrient information.'); } } Food.describe(); // '"Food" is a data type for storing macronutrient information.' |
Prototype methods
Any method that isn’t a constructor or a static method is prototype method. The name comes from the fact that we used to achieve this functionality by attaching functions to the .prototype of functions-as-constructors:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
"use strict"; // Using ES6: class Food { constructor (name, protein, carbs, fat) { this.name = name; this.protein = protein; this.carbs = carbs; this.fat = fat; } toString () { return `${this.name} | ${this.protein}g P :: ${this.carbs}g C :: ${this.fat}g F`; } print () { console.log( this.toString() ); } } // In ES5: function Food (name, protein, carbs, fat) { this.name = name; this.protein = protein; this.carbs = carbs; this.fat = fat; } // The name "prototype methods" presumably comes from the fact that we // used to attach such methods to the '.prototype' old-school functions-as-constructors. Food.prototype.toString = function toString () { return `${this.name} | ${this.protein}g P :: ${this.carbs}g C :: ${this.fat}g F`; }; Food.prototype.print = function print () { console.log( this.toString() ); }; |