@singuerinc


2014.01.07 by Nahuel Scotti | 1 min read

Extend with plain Javascript


Hoy un método rápido para simular herencia en Javascript.

function extend(Child, Parent) {
    Child.prototype = (
        function (){
            function F() {};
            F.prototype = Parent.prototype;
            return new F;
        }
    )();
    Child.prototype.constructor = Child;
    Child.parent = Parent.prototype;
    return Child.prototype;
};

Y cómo lo usamos:

var Animal = (function(){
    var Clazz = function(){
        this.name = 'Animal';
    };
    var p = extend(Clazz, Object);
    p.run = function() {
        console.log(this.name + ' running.');
    }
    return Clazz;
})();

var Dog = (function(){
    var Clazz = function(){
        this.name = 'Dog';
    };
    extend(Clazz, Animal);
    return Clazz;
})();

var cat = new Animal();
cat.run() // "Animal runnning"

var dog = new Dog();
dog.run() // "Dog runnning"
  • #javascript
  • #prototype