简体   繁体   English

原型 inheritance

[英]Prototypal inheritance

I have this object, dive :我有这个 object, dive

var dive = new Foo.Bar();

And Foo.Bar looks like this: Foo.Bar看起来像这样:

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

I'd like dive to have all the prototypes of another, existing object, however.但是,我想dive了解另一个现有 object 的所有原型。 Let's say window.Cow.prototype is:假设window.Cow.prototype是:

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

What do I need to do to Foo.Bar so that I can do this:我需要对Foo.Bar做什么才能做到这一点:

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这是一个没有 Bar 构造函数jsFiddle的工作示例

Thank you for the start, jimbojw, You were close: but you gave me enough information to get it:谢谢你的开始,jimbojw,你很接近:但你给了我足够的信息来得到它:

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:如果你想封装Foo.Bar.prototype =你可以在不改变默认构造函数行为的情况下做到这一点:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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