代码之家  ›  专栏  ›  技术社区  ›  maroodb

如何在nodejs内部调用导出函数?

  •  1
  • maroodb  · 技术社区  · 6 年前

    我试图调用nodejs模块内的导出函数。

    exports.sayHello = function (msg) {
     console.log(msg) 
    }
    
    function run(msg) {
      this.sayHello(msg);
    }
    
    run("hello");
    

    当我运行这个脚本时 typeerror:this.sayhello不是函数

    1 回复  |  直到 6 年前
        1
  •  4
  •   T.J. Crowder    6 年前

    只需声明它与导出它分开(并且不要使用 this 调用时,您没有将其附加到对象上):

    function sayHello(msg) {
     console.log(msg) 
    }
    exports.sayHello = sayHello;
    
    function run(msg) {
      sayHello(msg);
    }
    
    run("hello");
    

    也就是说,你 能够 通过它调用它 exports :

    exports.sayHello = function (msg) {
     console.log(msg) 
    }
    
    function run(msg) {
      exports.sayHello(msg); // <===
    }
    
    run("hello");
    

    ……但这对我来说似乎有点迂回,尽管我被告知这有助于测试,例如 in this example .