Last active
September 30, 2023 03:01
-
-
Save juliocesar/5507154 to your computer and use it in GitHub Desktop.
ES6 - classes
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
// ES6 classes example | |
// =================== | |
// Currently, with prototypal inheritance: | |
var Person = function(name) { | |
this.name = name; | |
}; | |
Person.prototype.talk = function(words) { | |
console.log(words); | |
} | |
Person.prototype.step = function(direction) { | |
console.log('Stepping ' + direction); | |
} | |
Person.prototype.walk = function(steps) { | |
for (var i = 0; i < steps; i++) | |
this.step('forward'); | |
} | |
// And in ES6 using classes. We now have constructor() and short-form | |
// method declaration. | |
class Person { | |
constructor(name) { | |
this.name = name; | |
} | |
talk(words) { | |
console.log(words); | |
} | |
step(direction) { | |
console.log('Stepping ' + direction); | |
} | |
walk(steps) { | |
for (var i = 0; i < steps; i++) | |
this.step('forward'); | |
} | |
} | |
// Inheritance in ES6, using super() in a method overridden. | |
class Troll extends Person { | |
walk(steps) { | |
if (steps.length > 5) throw("Too much effort"); | |
super(steps); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment