javascript inheritance from multiple objects

后端 未结 3 746
死守一世寂寞
死守一世寂寞 2020-12-20 07:02

I\'m not very well aquainted with javascript inheritance, and I\'m trying to make one object inherit from another, and define its own methods:

function Foo()         


        
3条回答
  •  感动是毒
    2020-12-20 07:28

    One solution would be:

    function FooB() {}
    var p = new Foo();
    p.methodA = function(){...}
    p.methodB = function(){...}
    p.methodC = function(){...}
    ...
    
    FooB.prototype = p;
    

    Update: Regarding expanding with an existing object. You can always copy the existing properties of one object to another one:

    FooB.prototype = new Foo();
    var proto = {
         /*...*/
    };
    
    for(var prop in proto) {
        FooB.prototype[prop] = proto[prop];
    }
    

    As long as proto is a "plain" object (i.e. that does not inherit from another object) it is fine. Otherwise you might want to add if(proto.hasOwnProperty(prop)) to only add non-inherited properties.

提交回复
热议问题