理解javascript函数声明

时间:2021-07-16 21:39:58

标签: javascript jquery

我知道 $ 是 jQuery 的别名。下面的代码将一个匿名函数传递给 $ 函数,它可以接受一个回调函数。

$(document).ready(function() {
    // ...
});

完美。它简单明了。但是在其中一个网站中,我看到以下两个文件,但不明白它在做什么。

文件 1

(function($, window, document, ns) {
    "use strict";
    ...
    ...
})
($, window, document, Granite.author);

文件 2

(function($,document) {
    "use strict";
    ...
    ...
})(Granite.$, document);

谁能帮助我理解我们传递的 $、窗口、文档、ns 等内容?

2 个答案:

答案 0 :(得分:1)

这不一定是 jQuery 概念。它正在创建一个函数并立即调用它。

像这样:

(function (argument) { 
    console.log(argument) 
})("This is being passed to the function")

另一种使用箭头函数的方法是

((argument) => { console.log(argument) })("This is being passed to the arrow function")

答案 1 :(得分:-1)

如果你想要一个调用自己的函数,你可以在 (function hello(){ console.log("你好") })()

这会自动调用函数并记录“hello”