JavaScript:闭包帮助
我有一个空的 .js 文件,其中包含以下代码:
Cart.CheckoutNow = {
...
}
// Alias
if (typeof(CheckoutNow) === 'undefined') {
CheckoutNow = Cart.CheckoutNow;
}
else {
alert('CheckoutNow is already a variable in window.');
}
如何让 // Alias
代码出现在页面顶部,但在声明 Cart.CheckoutNow 之后执行它?
这可行,但我不喜欢你必须在底部调用alert():
alias = function() {
if (typeof(CheckoutNow) === 'undefined') {
CheckoutNow = Cart.CheckoutNow;
}
else {
alert('CheckoutNow is already a variable in window.');
}
};
Cart.CheckoutNow = {
...
};
alias();
I have an empty .js file with this code in it:
Cart.CheckoutNow = {
...
}
// Alias
if (typeof(CheckoutNow) === 'undefined') {
CheckoutNow = Cart.CheckoutNow;
}
else {
alert('CheckoutNow is already a variable in window.');
}
How can I have the // Alias
code appear at the top of the page, but have it execute after Cart.CheckoutNow is declared?
This would work, but I don't like that you have to call alert() at the bottom:
alias = function() {
if (typeof(CheckoutNow) === 'undefined') {
CheckoutNow = Cart.CheckoutNow;
}
else {
alert('CheckoutNow is already a variable in window.');
}
};
Cart.CheckoutNow = {
...
};
alias();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果没有解释为什么要尝试这样做,我会猜测这是为了更好的代码组织。如果是这种情况,我会将您的 JavaScript 分成多个文件,并按以下顺序包含在您的页面上:
Without an explanation of why you're trying to do this, I'm going to guess that it's for better code organization. If that's the case, I would split your JavaScript up into multiple files something along the lines of this, and to be included on your page in this order:
我不确定这是否真的是您想要做的,但如果您确定,那么您想要的是:
I'm not sure this is really what you want to be doing, but if you're sure, then what you want is:
您必须在函数中定义 Alias 并将其称为 body 的 onload 事件。
You would have to define Alias in a function and call it onload event of body.