javascript inheritance from multiple objects

后端 未结 3 744
死守一世寂寞
死守一世寂寞 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: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();
    

提交回复
热议问题