Subclassing a class with required parameters in JavaScript

后端 未结 3 781
情歌与酒
情歌与酒 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: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 :)

提交回复
热议问题