Search code examples
javascriptinheritanceprototype-programming

Prototypal inheritance


I have this object, dive:

var dive = new Foo.Bar();

And Foo.Bar looks like this:

var Foo = {
    Bar: function() {
        ...
        return function() {
        // do stuff, no return
        };
    }
};

I'd like dive to have all the prototypes of another, existing object, however. Let's say window.Cow.prototype is:

{
    moo: function() { ... },
    eat: function() { ... }
}

What do I need to do to Foo.Bar so that I can do this:

dive.moo();
dive.eat();

Solution

  • Thank you for the start, jimbojw! You were close, but you gave me enough information to get it:

    function Cow() {
        return {
            talk: function() {
                 alert("mooo");   
            }
        };   
    }
    
    var Foo = {
        Bar: function() {
            function result() {
                alert("Foo.Bar says...");
            };
            result.prototype = new Cow();
            return new result;
        }
    };
    
    new Foo.Bar().talk();