Subclassing a class with required parameters in JavaScript

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

提交回复
热议问题