最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to self-reference NodeJS Module? - Stack Overflow

programmeradmin0浏览0评论

I have a module that I'm exporting. I need one function to call another function. Here's a simplified version of what I'm trying to do.

module.exports = {
  isEven: (number) => {
    return (number%2 == 0)
  },
  isTenEven: () => {
    return isEven(10)
  }
}

The code above throws isEven is not defined when moduleName.isTenEven() is called.

It makes sense why it fails. But how would you rewrite it? (While maintaining the singleton pattern)

I have a module that I'm exporting. I need one function to call another function. Here's a simplified version of what I'm trying to do.

module.exports = {
  isEven: (number) => {
    return (number%2 == 0)
  },
  isTenEven: () => {
    return isEven(10)
  }
}

The code above throws isEven is not defined when moduleName.isTenEven() is called.

It makes sense why it fails. But how would you rewrite it? (While maintaining the singleton pattern)

Share Improve this question asked Jan 5, 2020 at 23:14 DruDru 9,83014 gold badges51 silver badges68 bronze badges 0
Add a ment  | 

6 Answers 6

Reset to default 5

Define the functions first, then export them:

const isEven = (number) => number % 2 === 0
const isTenEven = () => isEven(10)

module.exports = {
  isEven,
  isTenEven
}

The object is only used to group the functions together. There's nothing really OO about it so define the functions separately. Construct the object at the end.

const isEven = number => number % 2 === 0;
const isTenEven = () => isEven(10);
module.exports = { isEven, isTenEven };

Maybe just do this? Define then export.

const isEven = number => number % 2 === 0;

module.exports = {
  isEven,
  isTenEven: () => isEven(10)
};

Just to add one more solution to the mix. You don't have to define the function elsewhere. Since the object declaration is plete before the function gets called, you can refer to it via module.exports or via exports like this:

module.exports = exports = {
  isEven: (number) => {
    return (number%2 === 0)
  },
  isTenEven: () => {
    return exports.isEven(10)
  }
}

If you were doing this in a lot of methods, you could define a shorter variable name for the exported object and refer to it.

If you can afford Babel or a version of Node.js that supports import/export statements you could also do:

export const isEven = num => num % 2 === 0;
export const isTenEven = () => isEven(10);

Inside JS object literal using this refers to the object itself so you can have:

module.exports = {
  isEven: (number) => {
    return (number%2 == 0)
  },
  isTenEven: function () {
    return this.isEven(10)
  }
}
发布评论

评论列表(0)

  1. 暂无评论