简体   繁体   中英

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();
var Foo = {
    Bar: function() {
        //...
        return this; // technically unnecessary, implied by 'new' operator
    }
};

Foo.Bar.prototype = new Cow(); // the secret sauce

dive = new Foo.Bar();

dive.moo(); // moo's like a Cow

Here is a working example without the Bar constructor jsFiddle

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();

If you want to encapsulate Foo.Bar.prototype = you can do it without changing default constructor behavior:

function Cow() {
  this.talk =  function() {
    alert("mooo")
  }
}

var Foo = {
  Bar: function() {
    var constructor = function() {
      this.eat = function() {
        alert("gulp")
      }
    }
    constructor.prototype = new Cow()
    return constructor
  }()
}

var foo = new Foo.Bar()
foo.talk()
foo.eat()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM