Created
May 18, 2018 13:45
-
-
Save jmcmaster/d29eb317caf8475487db98dc770c5e8f to your computer and use it in GitHub Desktop.
OOP in JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Demonstrates a few ways to achieve OOP with JavaScript | |
| // Solution 1 | |
| function playerCreator(name, score) { | |
| var newPlayer = Object.create(playerFunctionStore); | |
| newPlayer.name = name; | |
| newPlayer.score = score; | |
| return newPlayer; | |
| } | |
| var playerFunctionStore = { | |
| getName: function() { | |
| return this.name; | |
| }, | |
| increment: function() { | |
| return this.score++; | |
| } | |
| }; | |
| var player1 = playerCreator('Jeffrey', 3); | |
| player1.increment(); | |
| // console.log(player1); | |
| // console.log(player1.__proto__); | |
| // Solution 2 | |
| function playerCreator(name, score) { | |
| this.name = name; | |
| this.score = score; | |
| } | |
| playerCreator.prototype.getName = function() { | |
| return this.name; | |
| }; | |
| playerCreator.prototype.increment = function() { | |
| return this.score++; | |
| }; | |
| var player2 = new playerCreator('Jason', 4); | |
| player2.increment(); | |
| // console.log(player2); | |
| // console.log(player2.__proto__); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment