javascript函数后括号中的值 [英] Values in parentheses after javascript function
问题描述
我正在尝试重新设定我在SO上的答案中找到的一些Javascript代码。但我想首先更好地理解它的语法。它的大纲是:
I'm trying to re-purpose some Javascript code I found linked in an answer on SO. But I would like to understand its syntax better first. Its outline is:
(function (root, ns, factory) {
// some code
} (window, 'detectZoom', function() {
// some more code
}));
请参阅这篇文章以引用完整代码。
See accepted answer in this post for the reference to the full code.
我理解最终结果是如何实现的,但我不太清楚内部(...)块如何与第一个相关,或者它内部的逗号分隔列表告诉编译器。
I understand how the end-result is achieved, but I don't quite know how the inner (...) block relates to the first, or what the comma separated list inside it tells the compiler.
有人可以解释一下吗?谢谢。
Can someone explain? Thanks.
推荐答案
有一个匿名函数有三个参数( root
, ns
, factory
)立即被调用。
There is an anonymous function taking three parameters (root
, ns
, factory
) which is immediately invoked.
-
root
取值`窗口。 -
ns
取值'detectZoom'
-
factory
获取回调函数的值(也是匿名的)
root
takes the value of`window.ns
takes the value of'detectZoom'
factory
takes the value of callback function (also anonymous)
解释:
(function (root, ns, factory) {
// the body of the anonymous function
} (window, 'detectZoom', function() {
// the body of the 'factory' callback
}));
要分解它,如何分四步获取此代码:
To break it apart, how to get to this code in four steps:
1.
// Anonymous function.
(function (root, ns, factory) {/* body */});
2.
// Anonynmous function, immediately invoked
(function (root, ns, factory) {/* body */})(); // parentheses mean it's invoked
3.
// Callback as a separate argument
var cbk = function () {};
(function (root, ns, factory) {/* body */})(window, 'detectZoom', cbk);
4.
// Callback as an anonymous function
(function (root, ns, factory) {/* body */})(window, 'detectZoom', function () {});
您可以将代码重写为更详细:
You could rewrite your code to be more verbose:
var outer = function (root, ns, factory) {
// the body
};
var callback = function () {
// the body
};
outer(window, 'detectZoom', callback);
这篇关于javascript函数后括号中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!