JavaScript inheritance: when constructor has arguments

后端 未结 4 2102
傲寒
傲寒 2020-12-13 08:47

Using pure JavaScript to do inheritance, this is what I usually do:

function A() {}
A.prototype.run = function () {};

function B() {}
B.prototype = new A;
B         


        
4条回答
  •  隐瞒了意图╮
    2020-12-13 09:22

    Well, if you want to make B.prototype an object that inherits from A.prototype, without executing the A constructor, to avoid all possible side-effects, you could use a dummy constructor to do it, for example:

    function tmp() {}
    tmp.prototype = A.prototype;
    B.prototype = new tmp();
    B.prototype.constructor = B;
    

    You could create a function to encapsulate the logic of the creation of this new object, e.g.:

    function inherit(o) {
      function F() {}; // Dummy constructor
      F.prototype = o; 
      return new F(); 
    }
    
    //...
    B.prototype = inherit(A.prototype);
    B.prototype.constructor = B;
    

    If you target modern browsers, you could use the ECMAScript 5 Object.create method for the same purpose, e.g.:

    B.prototype = Object.create(A.prototype);
    B.prototype.constructor = B;
    //..
    

提交回复
热议问题