所以我要经历一个' Modules' Eloquent JS书的章节和我遇到了函数(导出)部分的问题。
(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(1));
返回
Cannot set property "weekDay" of undefined
然而,在本书网站的在线编辑器中,完全相同的代码运行没有问题并返回"星期一"。
我想知道Adobe Brackets是否存在问题。
答案 0 :(得分:1)
使用不依赖于在this
作为全局对象的全局脚本范围中执行的模块模式。我推荐
var weekDay = (function (exports) {
var names = ["Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"];
return {
name: function (number) {
return names[number];
},
number: function (name) {
return names.indexOf(name);
}
};
}());
是的,这是由您的环境引起的,但代码首先是脆弱的。如果你想继续使用那个exports
的东西,你也可以
var weekDay;
(function (exports) {
…
})(weekDay = {});
或者选中How to get the global object in JavaScript?和Getting a reference to the global object in an unknown environment in strict mode。