We could create each game piece individually, but rewriting the functionality for each piece will take a lot of time and make it harder to revise the code. So, we are going to create a "factory" to create new instances of GamePieces - such as pawn1W and queenB which will all share some common traits and methods.
1) Functional - with the functional instantiation pattern, we will use a class production function (GamePieces) to create a new instance (pawn1W) of a piece for the board. The functional style will put a copy of each of the included methods (moveTo) onto each GamePieces instance.
2) Functional Shared - this instantiation pattern is just like functional, but with one large bonus. With this instantiation pattern, we don't have to give all of the methods to each instance we create. Instead, we use _.extend to give each instance a reference to where the method can be found.
3) Prototypal - instead of using _.extend to copy over a reference to each method, this instantiation pattern uses Object.create() to create an object which will point at another object in cases where the instance itself does not contain that method/value. Take a look at this and let's meet below the graphic to discuss...
...so, when .moveTo is called for pawn1W, the compiler will not find that method on pawn1W, but because of Object.create(pieceFuncs), it will know to go to the pieceFuncs object to look for .moveTo.
As you can see by the comment lines above, there is another feature that we need to consider with this style. It uses the 'new' keyword. The 'new' keyword is used when creating the object and it basically works to replace the Object.create() and return lines of code seen in the prototypal style.
5) ES6 - ES6 introduces classes as a new instantiation pattern. Syntactically, class is not a function or an object - it is something new to ES6. Look through the following code, and let's take a moment to reflect...
While the syntax is new, this constructor function handles creation of objects about the same as the pseudoclassical style. Notice also the syntax to include methods on this class. Although it may not be intuitive, the new Class construct is going to save that method to the prototype object of the constructor.
While you can use any of these instantiation styles, the latter styles require less copying of methods which becomes important as systems scale. So, learn the ES6 and use it to impress potential employers.
Special thanks to the youtube channel "hola〈code/〉" for helping me to understand these concepts. Here are helpful links for followup research:
Top comments (0)