脚本开头的“(function() {”的用途(仅限 GreaseMonkey?)

发布于 2024-10-08 11:23:29 字数 299 浏览 1 评论 0原文

我对 JavaScript 还很陌生,我正在自学。我目前正在创建和调整 GreaseMonkey 脚本。我注意到大多数简单的脚本(即那些不需要命名函数的脚本)直接进入主代码,但有些脚本是这样设置的:

(function() {  
    //main code here  
})();

这种类型的编码有什么意义?我已经注释掉了顶部和底部,并且脚本仍然运行完全相同。

它只是一个编码标准,还是真的有功能?而且,正如我的标题所问的,这是 GreaseMonkey 特有的事情,还是我应该一直做的事情?

I'm pretty new to JavaScript, which I am learning on my own. I'm currently creating and tweaking GreaseMonkey scripts. I've noticed that most simple scripts (i.e. those with no need for named functions) go straight into the main code, but some instead are set up like this:

(function() {  
    //main code here  
})();

What is the significance of this type of coding? I've commented out both the top and bottom, and the script still runs exactly the same.

Is it just a coding standard, or does it actually have a function? And, as my title asks, is it something specific to GreaseMonkey, or something that I should do all the time?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

猥︴琐丶欲为 2024-10-15 11:23:29

该技术有效地创建了一个私有名称空间,只能由该脚本访问。例如,以下代码:

(function() {
    var a = 5;
})();

将对全局命名空间没有影响a变量被闭包捕获,因此window.a将不受影响)。这是一种非常好的方法,可以通过使许多脚本根本不是全局变量来防止它们相互干扰。我在编写任何 JavaScript 时都使用这种技术,而不仅仅是 Greasemonkey 脚本,并且强烈推荐将其作为编写库时的最佳实践。

如果您想将某些函数公开给其他 JavaScript 代码,而不是完全隔离您的脚本,您可以执行以下操作:

var MyNamespace = (function () {
    var that = {};

    that.square = function(x) {
        return x*x;
    };

    return that;
})();

然后您可以从另一个脚本执行 MyNamespace.square(5) ,这将返回25.

This technique effectively creates a private namespace, accessible only to this script. For example, this code:

(function() {
    var a = 5;
})();

will have no effect on the global namespace (the a variable is captured by the closure, so window.a will not be affected). It's a very nice way to keep many scripts from stepping on each other's global variables, by making them not global at all. I use this technique all the time when writing any JavaScript, not just Greasemonkey scripts, and would strongly recommend it as a best practice when writing libraries.

If you wanted to expose some functions to other JavaScript code instead of completely isolating your script, you could do something like this:

var MyNamespace = (function () {
    var that = {};

    that.square = function(x) {
        return x*x;
    };

    return that;
})();

Then you could do MyNamespace.square(5) from another script, and this would return 25.

摇划花蜜的午后 2024-10-15 11:23:29

这是一个自执行的匿名函数。

它通常用于更改作用域,在此声明的所有变量/函数都将位于匿名函数的作用域中,而不是全局(窗口)作用域中。

It's a self executing anonymous function.

It's usually used to change the scope, all variables/functions declared inside this will be in the anonymous function's scope instead of the global (window) scope.

诗笺 2024-10-15 11:23:29

该代码有两个目的:

  1. 它将对象/变量保留在匿名函数范围内。这很重要,因为我们看到您可能有多个脚本文件,它们都可能共享相同的变量名称。如果他们这样做了,他们就可以替换变量值并真正破坏您的应用程序。

  2. 行尾的 () 调用声明的函数。换句话说,您在第一组括号内创建的匿名函数可以立即自动调用。除非将其分配给变量,否则没有其他方法可以调用它。这避免了在内存中创建变量,而只是在运行时调用函数。

The code serves two purposes:

  1. It keeps objects/variables local to the anonymous function scope. This is important as we see that you may have several script files that all might share the same variable name. If they did, they could replace the variables value and truly muck with your application.

  2. The () at the the end of the line calls the declared function. In other words, the anonymous function you created inside the first set of parentheses can automatically be called instantly. Unless you assigned it to a variable, there would be no other way to call it. This avoids creating a variable in memory and just calls the function at runtime.

离去的眼神 2024-10-15 11:23:29

对于那些从未听说过闭包的人来说,这是一个微教程:

假设我们有一个函数,

function sayHi() { alert('Hello'); }

我们可以通过这样做来调用这个函数:

sayHi();

上面就是所谓的命名函数,如果你不知道这意味着什么,那么这就是你的意思。想想当你听到函数这个词时,

在某些语言中,你不必命名函数,你可以将其留空,如下所示:

alert('Sup');
function() {alert('Hello'); }
3 + 1;
alert('Peace');

第 2 行完全有效。当然,第 2 行不会在您的页面中真正执行任何操作,就像第 3 行不会执行任何操作一样。这就是所谓的匿名函数。现在就像我们可以将变量分配给第 3 行一样:

result = 3 + 1;

我们可以对第 2 行执行相同的操作,如下所示:

myFunc = function() { alert('Hello'); };

我们可以像之前的 sayHi() 函数一样使用 myFunc 作为函数。我们调用它就像我们调用 sayHi() 一样。

sayHi();
myFunc();

现在,由于 javascript 被编写为通用的,像 [0, 1, 2].indexOf(1) 这样的东西可以工作,我们可以执行以下操作

func = function() { alert('hello'); };
func();
(function() { alert('hello'); })();

:第 2 行将完成与第 3 行相同的任务,因为第 3 行只是第 1 行和第 2 行的扩展版本。第 3 行的优点是,如果稍后有人在代码中使用 func 变量,它就不会不会对您自己的代码造成问题,而且在第 3 行函数中声明的任何变量(使用 var 关键字)都不会是函数外部的有效变量,在本例中这就是闭包。

Here's a micro-tutorial for those who never heard of closures:

Suppose we have a function

function sayHi() { alert('Hello'); }

We would call this function by doing this:

sayHi();

The above is whats called a named function, if you don't know what that means, then it's what you think of when you hear the word function

In some languages you don't have to name a function, you can leave it blank like so:

alert('Sup');
function() {alert('Hello'); }
3 + 1;
alert('Peace');

Line 2 is perfectly valid. Of course line 2 won't really do anything in your page, just like line 3 doesn't do anything. That is called an anonymous function. Now just like we can assign a variable to line 3 like:

result = 3 + 1;

We can do the same with line 2, like this:

myFunc = function() { alert('Hello'); };

And we can use myFunc as a function like the sayHi() function before. We call it just like we call sayHi()

sayHi();
myFunc();

Now since javascript is written to be versatile, where stuff like [0, 1, 2].indexOf(1) works, we can do the following:

func = function() { alert('hello'); };
func();
(function() { alert('hello'); })();

And line 1 & 2 will accomplish the same thing as line 3 since line 3 is just an expanded version of line 1 and 2. The advantage of line 3 is that if someone later on in the code uses a func variable it wouldn't cause a problem with your own code, also any variables declared in line 3's function (with a var keyword) won't be a valid variable outside of your function, which in this case is what a closure is.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文