代码之家  ›  专栏  ›  技术社区  ›  Peter Krauss

如何扩展模块的类?

  •  0
  • Peter Krauss  · 技术社区  · 6 年前

    我使用的是现代JavaScript(EC6+)代码 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!
    

    错误:“typeerror:c.test不是函数”

    1 回复  |  直到 6 年前
        1
  •  1
  •   Peter Krauss    6 年前

    bigInt is not a constructor function. 它是一个返回对象的普通函数。因此,你不能真正扩展它。

    下面是这个问题的简化示例:

    function Foo() {
      return {foo: 42};
    }
    
    class Bar extends Foo {
      constructor() {
        super();
      }
    }
    
    console.log(new Bar instanceof Bar);
    console.log(new Bar);

    返回的值 new Bar 返回的值是 Foo ,不扩展 Bar.prototype .


    如果只需要添加一个新方法, at least ,您可以修改原型:

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