Skip to content

Instantly share code, notes, and snippets.

@jmcmaster
Created May 18, 2018 13:45
Show Gist options
  • Select an option

  • Save jmcmaster/d29eb317caf8475487db98dc770c5e8f to your computer and use it in GitHub Desktop.

Select an option

Save jmcmaster/d29eb317caf8475487db98dc770c5e8f to your computer and use it in GitHub Desktop.
OOP in JavaScript
// 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