Last active
August 13, 2019 17:13
-
-
Save moonmaster9000/980e832b0f60ef91d85668c9fb49be9e to your computer and use it in GitHub Desktop.
Javascript Classes: es5 versus es6
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
//old school es5 syntax for creating a class | |
//advantage: lets you create private functions and state through closure | |
//disadvantage: looks weird if you learned OO through language like c++/java/ruby, etc. Doesn't support prototypical inheritance. | |
//constructor function | |
function MyES5Class(aPrivateVar){ | |
var aontherPrivateVar = "I'm a private variable! You can't access me from the outside." | |
this.publicVar = "I'm a public variable! You can access me from the outside!" | |
this.myPublicFunction = function(){ | |
//you can access private variables and functions in here (aPrivateVar, anotherPrivateVar, myPrivateFunction) | |
console.log("I'm a public function! You can call me from the outside!") | |
} | |
var myPrivateFunction = function(){ | |
console.log("I can only be called from within the instance. I'm private! I work through closure.") | |
} | |
} | |
let myES5Object = new MyES5Class("my data") | |
myES5Object.myPublicFunction() // works | |
myES5Object.myPrivateFunction() // BLOWS UP! This throws an exception, as myPrivateFunction is hidden from the outside world through closure encapsulation. | |
//new es6 syntax | |
//advantage: looks familiar to people who have learned OO through languages like c++/java/ruby, etc. Supports prototypical inheritance. | |
//disadvantage: doesn't allow for private fields or private methods. Boo! | |
class MyES6Class{ | |
constructor(someVar){ | |
this.someVar = someVar //you have to make these public :( | |
this.publicVar = "I'm a public variable! You can access me from the outside!" | |
} | |
myPublicFunction(){ | |
console.log("I'm a public function! You can call me from the outside!") | |
} | |
} | |
let myES6Object = new MyES6Class("my data") | |
myES6Object.myPublicFunction() // works | |
myES6Object.someVar // works, since fields can't be made private in the new class syntax | |
myES6Object.publicVar // works, since fields can't be made private in the new class syntax | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment