我试图在关于模块的部分中使用Eloquent Javascript运行这个简短的程序。
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关键字的方式有关。有人可以帮助我至少粗略地理解这种行为吗?
答案 0 :(得分:3)
Nir Levy的答案是正确的,但我也发布了这个答案,因为你在谈论模块。这就是你如何制作一段代码的模块。
//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')));
答案 1 :(得分:2)
在node.js这一行:
var weekDay = function() {}();
只生成一个未定义的变量weekDay,因为它所做的只是定义一个en空体(代码中为{}
)的函数并立即运行它。由于正文是空的(最重要的是,没有返回语句),因此它会产生未定义的
执行所需操作的方法是将整个定义放在此函数中,并定义要公开的内容,如下所示:
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")));
答案 2 :(得分:0)
将第一行更改为var weekDay = {};
,当你调用你的生命时,只需将你在第一行创建的内容放入其中。