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

时间:2015-10-12 10:32:35

标签: javascript node.js model-view-controller express

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

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

  

无法调用未定义的方法getName

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

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

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

5 个答案:

答案 0 :(得分:17)

我找到了解决方案: - )

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

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

答案 1 :(得分:8)

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

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

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

答案 2 :(得分:8)

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

"use strict";

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

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

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

答案 3 :(得分:0)

如果要在其他文件中本地使用此功能...

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

答案 4 :(得分:0)

我知道答案已经被接受,但是我觉得有必要在这个问题上加我的两分钱。

节点模块具有“单字母”性质,在模块内部时,您就是该模块。 我认为,至少在设计模式方面,可以更干净地访问内部模块方法,而无需thisself的副本。

如果this碰巧发送了单独的方法而忘记使用.bind,则可能会很危险。

使用self的副本是多余的,我们已经在Singleton行为模块中,为什么要避免引用自己呢?

请考虑以下这些:

选项1

// using "exports."

exports.utilityMethod = (..args) => {
     // do stuff with args
}

exports.doSomething = (someParam) => {
    // this always refers to the module
    // no matter what context you are in
    exports.utility(someParam)
}

选项2

// using module.exports

const utility = (..args) => {
   // do stuff with args
}

const doSomething = (someParam) => {
    // Inside the module, the utility method is available
    // to all members
    utility(someParam)
}

// either this
module.exports = {
 utility,
 doSomething,
}

// or 
module.exports = {
 customNameForUtility: utility,
 customNameForDoSomething: doSomething
}

这对于es6模块是相同的:

选项1(ES6)

export const utilityMethod = (..args) => {
     // do stuff with args
}

export const doSomething = (someParam) => {
    // this always refers to the module
    // no matter what context you are in
    utility(someParam)
}

选项2(ES6)

const utility = (..args) => {
   // do stuff with args
}

const doSomething = (someParam) => {
    // Inside the module, the utility method is available
    // to all members
    utility(someParam)
}

export default {
  doSomething,
  utility
}

// or 
export {
 doSomething,
  utility
}

再次,这只是一个意见,但看起来更简洁,并且在不同的实现中更加一致,并且没有使用单个this / self

相关问题