Peter Krauss
Peter Krauss

Reputation: 13930

How to extends a class of a module?

I am using modern Javascript (EC6+) code with node --experimental-modules.

import bigInt from 'big-integer';  // npm i big-integer

console.log(bigInt(333).toString(2)) // fine

class bigIntB4 extends bigInt {
    constructor(...args) {
       super(...args);
    }
    test() {
       console.log("Hello!")
    }
}

let c = new bigIntB4(333)  //fine
console.log(c.toString(2)) // fine
c.test()   // BUG!

Error: "TypeError: c.test is not a function"

Upvotes: 0

Views: 240

Answers (1)

Felix Kling
Felix Kling

Reputation: 816462

bigInt is not a constructor function. It's a normal function that returns an object. As such you cannot really extend it.

Here is a simplified example of the issue:

function Foo() {
  return {foo: 42};
}

class Bar extends Foo {
  constructor() {
    super();
  }
}

console.log(new Bar instanceof Bar);
console.log(new Bar);

The value returned by new Bar is the value returned by Foo, which does not extend Bar.prototype.


If you need only to add a new method, at least, you can modify the prototype:

bigInt.prototype.test = function () {
  console.log("Hello!");
};

Upvotes: 1

Related Questions