JavaScript inheritance: when constructor has arguments

后端 未结 4 2114
傲寒
傲寒 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:31

    Although this is an old topic, I thought I'd respond anyway. Two ways to do it:

    Although the Pseudo Classical way is the most popular, it has its down sides since it needs to call the parent constructor once in the child constructor and once while inheriting the prototype. Besides, the child's prototype will contain all the properties of the parent constructor which will anyway get overwritten when the child constructor is called. My personal choice is Prototypal Inheritance.

    1. Pseudo Classical Inheritance:

    function A(x, y) {} 
    A.prototype.run = function () {};
    function B(x, y) {
        A.call(this,x,y);
    }
    B.prototype = new A();
    B.prototype.constructor = B;
    

    2. Prototypal Inheritance:

    function A(x, y) {}
    A.prototype.run = function () {};
    function B(x, y) {
        A.call(this,x,y);
    }
    B.prototype = Object.create(A.prototype);
    B.prototype.constructor = B;
    

提交回复
热议问题