javascript inheritance from multiple objects

后端 未结 3 742
死守一世寂寞
死守一世寂寞 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:13

    You can use an extend function which copies the new members to the prototype object.

    function FooB() {}
    FooB.prototype = new FooA();
    
    extend(FooB.prototype, {
        /* other methods here */
    });
    

    extend

    /**
     * Copies members from an object to another object.
     * @param {Object} target the object to be copied onto
     * @param {Object} source the object to copy from
     * @param {Boolean} deep  whether the copy is deep or shallow
     */
    function extend(target, source, deep) {
        for (var i in source) {
            if (deep || Object.hasOwnProperty.call(source, i)) {
                target[i] = source[i];
            }
        }
        return target;
    }
    
    0 讨论(0)
  • 2020-12-20 07:19

    Each object can only have one prototype, so if you want to add to the prototype after inheriting (copying) it, you have to expand it instead of assigning a new prototype. Example:

    function Foo() {}
    
    Foo.prototype = {
        x: function(){ alert('x'); },
        y: function(){ alert('y'); }
    };
    
    function Foo2() {}
    
    Foo2.prototype = new Foo();
    Foo2.prototype.z = function() { alert('z'); };
    
    var a = new Foo();
    a.x();
    a.y();
    var b = new Foo2();
    b.x();
    b.y();
    b.z();
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题