gpt4 book ai didi

javascript - 函数(导出)返回错误 "Cannot set property ' weekDay' 未定义”

转载 作者:行者123 更新时间:2023-12-03 08:08:10 25 4
gpt4 key购买 nike

所以我正在阅读 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

但是,在本书网站上的在线编辑器中,完全相同的代码运行没有问题并返回“Monday”。

我想知道这是否是 Adob​​e Brackets 的问题。

最佳答案

使用不依赖于在全局脚本作用域中执行的模块模式,其中 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 .

关于javascript - 函数(导出)返回错误 "Cannot set property ' weekDay' 未定义”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34279840/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com