Skip to content

Instantly share code, notes, and snippets.

@juliocesar
Last active September 30, 2023 03:01
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juliocesar/5507154 to your computer and use it in GitHub Desktop.
Save juliocesar/5507154 to your computer and use it in GitHub Desktop.
ES6 - classes
// 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