How to extend existing constructor function in javascript?

后端 未结 1 1911
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-15 22:09

Let\'s suppose that I have the following object function:

function A(options){
 ...
}

Then I want to create a new function (B) that inherit

相关标签:
1条回答
  • 2021-01-15 22:52

    Just call A constructor with this

    function B(aOptions, bOptions) {
      A.call(this, aOptions);
    
      // do stuff with bOptions here...
    }
    

    Now to setup the prototype

    B.prototype = Object.create(A.prototype, {
      constructor: {
        value: B
      }
    });
    

    Now B will have the prototype methods from A.

    Any new methods added to B's prototype will not be available to A's prototype


    There's a couple other tweaks that can make your life easier too.

    function A(options) {
    
      // make `new` optional
      if (!(this instanceof A)) {
        return new A(options);
      }
    
      // do stuff with options here...
    }
    

    And do the same for B

    function B(aOptions, bOptions) {
    
      // make `new` optional
      if (!(this instanceof B)) {
        return new B(aOptions, bOptions);
      }
    
      // call parent constructor
      A.call(this, aOptions);
    
      // do stuff with bOptions here...
    }
    

    Now you can call A(options) or new A(options) to get the same result.

    Same with B, B(aOptions, bOptions) or new B(aOptions, bOptions) will get the same result.

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