Pattern: Constructor

Herencia con prototipos

by rulokc

HTML

<script src="http://amatiasq.com/fiddle-console.js"></script>
<a href="http://www.amatiasq.com/2012/01/javascript-conceptos-basicos-herencia-por-prototipos/" target="_blank">Referencia</a>

JavaScript

/*
No hay clases.
En la herencia se indica a un objeto que herede de otro.
*/
var padre1 = {
    hello : 'hello 1'
};
var hijo1 = {};
// todo objeto tienen una propiedad [[Prototype]] / __proto__
console.log(hijo1.__proto__ == Object.prototype);
hijo1.__proto__ = padre1;
console.log(hijo1.__proto__ == padre1);
console.log(hijo1.hello);

var padre2 = function() {};
// toda función tiene una propiedad prototype
padre2.prototype = {
    hello : 'hello 2'
};
// los objetos creados con la función como constructor
// tendran su [[Prototype]] apuntando a prototype
var hijo2 = new padre2();
console.log(hijo2.__proto__ == padre2.prototype);
console.log(hijo2.hello);

// usando extend()
function extend(proto) {
    function intermediario() { }
    intermediario.prototype = proto;
    return new intermediario;
}
var padre3 = {
    hello: 'hello 3'
};
var hijo3 = extend(padre3);
console.log(hijo3.__proto__ == padre3);
console.log(hijo3.hello);

// usando Object.create()
var padre4 = {
    hello: 'hello 4'
};
var hijo4 = Object.create(padre4);
console.log(hijo4.__proto__ == padre4);
console.log(hijo4.hello);