Subclassing a class with required parameters in JavaScript

后端 未结 3 782
情歌与酒
情歌与酒 2021-02-04 10:07

If subclassing a \"class\" in JavaScript is done like so:

var ParentClass = function() {
    // something
};


var ChildClass = function() {
    // something
};
         


        
相关标签:
3条回答
  • 2021-02-04 10:43

    A better way to inherit...

    var inherit = (function () {
      var F = function () {}; // cache function
      return function (C, P) { // Accepts Constructor and Parent
        F.prototype = P.prototype;
        // faster prototype chain lookup than direct instantiation
        C.prototype = new F(); 
        C._super = P.prototype;
        C.prototype.constructor = C; // for checking instanceof
      };
    }());
    
    0 讨论(0)
  • 2021-02-04 10:51

    Subclass it like this instead:

    function clone (obj) {
      if (!obj) return;
      clone.prototype = obj;
      return new clone();
    }
    
    var ParentClass = function() {
        // something
    };
    
    
    var ChildClass = function() {
        // something
    };
    
    ChildClass.prototype = clone(ParentClass.prototype);
    ChildClass.prototype.constructor = ChildClass; // if you want
    

    Now you don't have to worry about it, because you don't have to call the parent constructor to subclass it :)

    0 讨论(0)
  • 2021-02-04 10:54

    This is how its done:

    function Parent( a ) {
        this.a = a;
    }
    
    function Child( a, b ) {
        Parent.call( this, a ); // this is crucial
        this.b = b;
    }
    
    Child.prototype = Object.create( Parent.prototype );
    Child.prototype.constructor = Child;
    

    Live demo: http://jsfiddle.net/ECCgt/ (analyze the instances in the console)


    The way you're doing it

    ChildClass.prototype = new ParentClass();
    

    is a dirty hack which is broken and should be avoided. Use Object.create to set up the inheritance relationship between the two prototype objects.

    The second line

    Child.prototype.constructor = Child;
    

    is somewhat optional. We are correcting the constructor property because we had to overwrite Child.prototype in order to set up the inheritance. If you don't care about the constructor property, just leave out that line.

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