why do we use `Boy.prototype = new Human;` to simulate inheritance?

前端 未结 2 1093
北荒
北荒 2021-01-13 20:54

i don\'t get why everyone is using Boy.prototype = new Human; to simulate inheritance. Look, what we want is the function\'s of A right? we can do that without

2条回答
  •  有刺的猬
    2021-01-13 21:09

    A better option is to create an intermediate to hold the prototype.

    function extend(clazz, superclass) {
        var intermediate = function() {};
        intermediate.prototype = superclass.prototype;
        clazz.prototype = new intermediate();
        // Following line is optional, but useful
        clazz.prototype.constructor = clazz;
    }
    

    This avoids unnecessary copying, but still means that you don't need to instantiate an object that will do work in its constructor. It also sets up the prototype chain so that you can use instanceof. It also doesn't result in superclass prototype contamination which some inheritance antipatterns can.

    For completeness, your subclass should call the superclass constructor in its constructor, which you can do with Superclass.call(this);.

    EDIT: Since ES5, you can replace calls to extend with

    Subclass.prototype = Object.create(Superclass.prototype);
    

    which does the same thing.

提交回复
热议问题