Skip to content

Instantly share code, notes, and snippets.

@thebergamo
Created June 24, 2014 12:59
Show Gist options
  • Save thebergamo/9360ff96875aba2238f1 to your computer and use it in GitHub Desktop.
Save thebergamo/9360ff96875aba2238f1 to your computer and use it in GitHub Desktop.
Herança JS
function Animal() {
}
Animal.prototype.nascer = function() {
// ...
}
Animal.prototype.morrer = function() {
// ...
}
Animal.prototype.respirar = function() {
// ...
}
// criamos o construtor Gato
function Gato(nome) {
this.nome = nome
}
Gato.prototype = new Animal() // definimos que Gato usa Animal como protótipo
Gato.prototype.constructor = Gato // para que não fique com o valor do construtor do objeto usado como protótipo
Gato.prototype.miar = function() { // método miar apenas para Gato
// ...
}
// criamos o construtor Cachorro
function Cachorro(nome) {
this.nome = nome
}
Cachorro.prototype = new Animal() // definimos que Cachorro usa Animal como protótipo
Cachorro.prototype.constructor = Cachorro()
Cachorro.prototype.latir = function() {
// ...
}
var rex = new Cachorro('rex') // criamos um objeto do tipo Cachorro
rex.latir() // utilizando um método definido em Cachorro
rex.respirar() // utilizando um método herdado de Animal
rex.nome // retorna 'rex'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment