我知道答案已经被接受,但我觉得有必要在这个问题上加两分钱。
节点模块具有“单调”性质,在模块内部时,您就是模块。
在我看来,至少在设计模式方面,可以更干净地访问内部模块方法,而无需 this 或 self 的副本。
使用 this 可能很危险,如果碰巧发送了单独的方法并忘记使用 .bind。
使用self 的副本是多余的,我们已经在一个单例行为模块中,既然可以避免这种情况,为什么还要保留对自己的引用?
请考虑这些:
选项 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。