Javascript函数有(文档)最后打了?

Javascript function has (document) slapped on at the end?

本问题已经有最佳答案,请猛点这里访问。

我正在尝试编写一个简单的Facebook应用程序。 在我需要的代码中,我发现了这个:

1
2
3
4
5
6
7
8
  // Load the SDK asynchronously
  (function(d){
   var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
   if (d.getElementById(id)) {return;}
   js = d.createElement('script'); js.id = id; js.async = true;
   js.src ="//connect.facebook.net/en_US/all.js";
   ref.parentNode.insertBefore(js, ref);
  }(document));

为什么这个函数被包裹在()中并且(文档)最后被打了?
我以前没见过这种JavaScript法术。

感谢您的任何意见。


它是一个自执行函数,它将document作为参数传递。

这可以改写为:

1
2
3
4
5
var myFunc = function(d) {
    // code here
};

myFunc(document);

JavaScript has a feature known as implied globals. Whenever a name is used, the interpreter walks the scope chain backwards looking for a var statement for that name. If none is found, that variable is assumed to be global. If it’s used in an assignment, the global is created if it doesn’t already exist. This means that using or creating global variables in an anonymous closure is easy. Unfortunately, this leads to hard-to-manage code, as it’s not obvious (to humans) which variables are global in a given file.

Luckily, our anonymous function provides an easy alternative. By
passing globals as parameters to our anonymous function, we import
them into our code, which is both clearer and faster than implied
globals. Here’s an example:

引用自:https://stackoverflow.com/a/15777654/3086


您可以使用此语法创建一个闭包,该闭包具有在(document)中传递的值作为函数参数的参数。 这种风格通常用于这样的事情:

1
2
3
4
5
for (var x = 0; x < 10; x++) {
  (function(y) {
    $.ajax({ params: {value: y}})...
  })(x);
}

这样做是因为它允许您将一组特定的值强制到该上下文中,当您希望循环的特定值可用于从该迭代进行的ajax调用时,这将特别有用。