Skip to content

Instantly share code, notes, and snippets.

@viniceosm
Last active August 10, 2018 10:22
Show Gist options
  • Save viniceosm/606d027076ab123b6f0dc3c99e5e169f to your computer and use it in GitHub Desktop.
Save viniceosm/606d027076ab123b6f0dc3c99e5e169f to your computer and use it in GitHub Desktop.
Herança ES5 vs ES6 | super/extends
//---- ES6
class Pessoa {
constructor(nome) {
this._nome = nome;
}
falar(mensagem) {
console.log(`${this._nome}: ${mensagem}`);
}
}
class Funcionario extends Pessoa {
constructor(nome) {
super(nome);
}
trabalha() {
console.log(`${this._nome} está trabalhando.`);
}
}
let func = new Funcionario('Julia');
func.falar('Bom dia');
func.trabalha();
//---- ES5
function Pessoa(_nome) {
this._nome = _nome;
}
Pessoa.prototype.falar = function (mensagem) {
console.log(this._nome + ': ' + mensagem);
}
function Funcionario(_nome) {
// super
Pessoa.call(this, _nome);
}
//Metodos Funcionario
Funcionario.prototype.trabalha = function () {
console.log(this._nome + ' está trabalhando.');
}
// Funcionario extends Pessoa
extendss(Funcionario, Pessoa);
function extendss(classChild, classesParent) {
if (!Array.isArray(classesParent))
classesParent = [classesParent];
for (classParent of classesParent) {
var _metodosClassChild = classChild.prototype;
classChild.prototype = Object.create(classParent.prototype);
classChild.prototype.constructor = classChild;
// Constructor + outros metodos
for (key of Object.keys(_metodosClassChild)) {
classChild.prototype[key] = _metodosClassChild[key];
}
}
}
var func = new Funcionario('Julia');
func.falar('Bom dia');
func.trabalha();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment