Javascript – 导出Node.js与浏览器

我试图从模块上的部分运行这个简短的程序。

var weekDay = function() {}(); (function(exports) { var names = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; exports.name = function(number) { return names[number]; }; exports.number = function(name) { return names.indexOf(name); }; })(this.weekDay = {}); console.log(weekDay.name(weekDay.number("Saturday"))); 

正确的输出应该是// -> Saturday

它在浏览器中完美工作。 但是,当我尝试在Node解释器中运行它时,出现此错误:

 TypeError: Cannot read property 'name' of undefined 

我只能假设它与Node处理exports关键字的方式有关。 有人能帮助我至less对这种行为有一个粗略的理解吗?

       

网上收集的解决方案 "Javascript – 导出Node.js与浏览器"

Nir Levy的答案是正确的,但是我也发布了这个答案,因为你在谈论Modules。 这是你如何制作一段代码的模块。

 //create your module like this and put this module in a separate file (ex. weekDay.js) var weekDay = (function() { var names = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; var name = function(number) { return names[number]; }; var number = function(name) { return names.indexOf(name); }; return { number: number, name: name } })(); //it's a self executing function //exporte module module.exports = weekDay //to get your module (in another file) var weekDayModule = require('./weekDay'); //path to module console.log(weekDayModule.name(weekDayModule.number('Saturday'))); 

在node.js中这一行:

 var weekDay = function() {}(); 

只是生成一个未定义的variablesweekDay,因为它所做的只是定义一个空的主体(代码中的{}函数并立即运行。 由于主体是空的(最重要的是,没有返回声明),它产生未定义

做你想做的事情的方法是将整个定义放在这个函数中,并且定义要暴露的东西,像这样:

 var weekDay = function() { var names = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; var name = function(number) { return names[number]; }; var number = function(name) { return names.indexOf(name); }; return { number: number, name: name } }(); console.log(weekDay.name(weekDay.number("Saturday"))); 

将第一行更改为var weekDay = {}; 当你援引你的生命时,就把你刚才在第一行创build的东西放进去。