匿名自调用 JavaScript 函数 - 返回多个对象
如果我有原始函数(作为示例):
var x = function() { alert('tadaaa'); return 1; }
var y = function() { alert('tadaaa'); return 1; }
并且我已经将其制作成一个自调用的匿名 JS 函数,如下所示:
(function() {
var x = function() { alert('tadaaa'); return 1; }
var y = function() { alert('tadaaa'); return 1; }
})()
我在做一些自相矛盾的事情吗?我想将 x 和 y 作为全局变量访问,但自调用匿名函数在其他领域很有用,我现在不详细介绍 - 我只想保留它。
我应该做类似的事情:
var x= (function() {
var x = function() { alert('tadaaa'); return 1; }
var y = function() { alert('tadaaa'); return 1; }
// Should I be doing something like
return x
})()
还是
var x= (function() {
var x = function() { alert('tadaaa'); return 1; }
return x
})()
var y = (function() {
var x = function() { alert('tadaaa'); return 1; }
return y
})()
看起来有点多余?
If I have original function (as an example):
var x = function() { alert('tadaaa'); return 1; }
var y = function() { alert('tadaaa'); return 1; }
and I've gone ahead and made this into a self-invoking anonymous JS function, as such:
(function() {
var x = function() { alert('tadaaa'); return 1; }
var y = function() { alert('tadaaa'); return 1; }
})()
am I doing something paradoxical? I'd like to access x and y as global variables, but the self-invoking anonymous function is useful in other areas that I'm not going into detail right now - I just want to keep it.
Should I be doing something like:
var x= (function() {
var x = function() { alert('tadaaa'); return 1; }
var y = function() { alert('tadaaa'); return 1; }
// Should I be doing something like
return x
})()
or
var x= (function() {
var x = function() { alert('tadaaa'); return 1; }
return x
})()
var y = (function() {
var x = function() { alert('tadaaa'); return 1; }
return y
})()
seems somewhat redundant?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不确定这一切的目标是什么,但也许您可以在一个对象中返回两个函数,如下所示:
这基本上就是模块模式的含义(例如,请参见 http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth)。
很好!当然,这取决于您的需要。
I'm not sure what the goal of al this is, but maybe you could return both functions in an object, like so:
This is basically what the Module Pattern is about (see for example http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth).
It's good! Depending on what you need, of course.
你可以:
You can: