Call a “local” function within module.exports from another function in module.exports?

前端 未结 8 1988
囚心锁ツ
囚心锁ツ 2020-11-30 16:24

How do you call a function from within another function in a module.exports declaration?

app.js
var bla = require(\'./bla.js\');
console.log(bl         


        
8条回答
  •  醉梦人生
    2020-11-30 16:44

    Starting with Node.js version 13 you can take advantage of ES6 Modules.

    export function foo() {
        return 'foo';
    }
    
    export function bar() {
        return foo();
    }
    

    Following the Class approach:

    class MyClass {
    
        foo() {
            return 'foo';
        }
    
        bar() {
            return this.foo();
        }
    }
    
    module.exports = new MyClass();
    

    This will instantiate the class only once, due to Node's module caching:
    https://nodejs.org/api/modules.html#modules_caching

提交回复
热议问题