gpt4 book ai didi

JavaScript 模块

转载 作者:行者123 更新时间:2023-12-02 20:15:03 31 4
gpt4 key购买 nike

我想知道是否可以将此代码更改为仅调用 MyModule.RED 而不是 MyModule.COLORS.RED。我尝试将 mod 设置为变量来存储颜色,但似乎不起作用。难道是我方法不对?

(function() {
var mod;

// Create the global, and also give ourselves a convenient alias for it (`mod`)
window.MyModule = mod = {};

// Colors
mod.COLORS = {
RED: "#FF0000",
BLUE: "#0000FF",
// ...
GREEN: "#00FF00"
};

mod.testQuery = MyModule_testQuery;
function MyModule_testQuery() {
// Do something
}

})();

alert(MyModule.COLORS.RED); // #FF0000
MyModule.testQuery(); // Do something
<小时/>

编辑

(function() {
var mod;

// Create the global, and also give ourselves a convenient alias for it (`mod`)
window.MyModule = mod = {};

// Colors
mod.COLORS = {
RED: "#FF0000",
BLUE: "#0000FF",
// ...
GREEN: "#00FF00"
};

var colors = mod.COLORS;

mod.testQuery = MyModule_testQuery;
function MyModule_testQuery() {
// Do something
}

})();

alert(colors.RED); // #FF0000
MyModule.testQuery(); // Do something

最佳答案

// Create the global, and also give ourselves a convenient alias for it (`mod`)
var mod;
window.MyModule = mod = {
RED: "#FF0000",
BLUE: "#0000FF",
// ...
GREEN: "#00FF00"
};

或者如果您想节省打字时间:

var cols = mod.COLORS;
cols.RED;

关于JavaScript 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6415751/

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