Javascript Node JS 在 module.exports 中调用“本地”函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33078967/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:36:33  来源:igfitidea点击:

Node JS call a "local" function within module.exports

javascriptnode.jsmodel-view-controllerexpress

提问by sravis

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

如何从 module.exports 声明中的另一个函数中调用函数?

I have MVC structure node js project and a controller called TestController.js. I want to access method within controller, but using thiskeyword gives below error:

我有 MVC 结构节点 js 项目和一个名为 TestController.js 的控制器。我想访问控制器内的方法,但使用this关键字会出现以下错误:

cannot call method getName of undefined

无法调用未定义的方法 getName

"use strict"
module.exports = {
    myName : function(req, res, next) {
        // accessing method within controller
        this.getName(data);
    },

    getName : function(data) {
        // code
    }
}

How do I access methods within controller?

如何访问控制器中的方法?

回答by sravis

I found the solution :-)

我找到了解决方案:-)

"use strict"
var self = module.exports = {
    myName : function(req, res, next) {
        // accessing method within controller
        self.getName(data);
    },

    getName : function(data) {
        // code
    }
}

回答by Mate Hegedus

You can access the getNamefunction trough module.exports. Like so:

您可以访问该getName功能槽module.exports。像这样:

"use strict"
module.exports = {
    myName : function(req, res, next) {
        // accessing method within controller
        module.exports.getName(data);
    },

    getName : function(data) {
        // code
    }
}

回答by severin.julien

Maybe you could do it like this. It reduce nesting. And all your export is done at the end of your file.

也许你可以这样做。它减少了嵌套。所有导出都在文件末尾完成。

"use strict";

var _getName = function() {
    return 'john';
};

var _myName = function() {
    return _getName();
};

module.exports = {
    getName : _getName,
    myName : _myName
};

回答by EddieB

If you want to use the function locally AND in other files...

如果您想在本地和其他文件中使用该功能...

function myFunc(){
    return 'got it'
}
module.exports.myFunc = myFunc;