Created
November 25, 2019 14:27
-
-
Save sag1v/9851ff55f1ee80337882e45b411e4f2e to your computer and use it in GitHub Desktop.
Markdium-JavaScript - The prototype chain in depth
This file contains 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
function Player(userName, score) { | |
this.userName = userName; | |
this.score = score; | |
} | |
Player.prototype.setScore = function(newScore) { | |
this.score = newScore; | |
} | |
function PaidPlayer(userName, score, balance) { | |
this.balance = balance; | |
/* we are calling "Player" without the "new" operator | |
but we use the "call" method, | |
which allows us to explicitly pass a ref for "this". | |
Now the "Player" function will mutate "this" | |
and will populate it with the relevant properties */ | |
Player.call(this, userName, score); | |
} | |
PaidPlayer.prototype.setUserName = function(newName) { | |
this.userName = newName; | |
} | |
// link PaidPlayer.prototype object to Player.prototype object | |
Object.setPrototypeOf(PaidPlayer.prototype, Player.prototype); | |
const player1 = new Player('sag1v', 700); | |
const paidPlayer = new PaidPlayer('sarah', 900, 5); | |
console.log(player1) | |
console.log(paidPlayer) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment