JavaScript和Facebook - 语法解释

时间:2011-05-19 10:42:38

标签: javascript facebook

我是JavaScript和Facebook SDK的新手。有人可以用英文描述以下功能:

  window.fbAsyncInit = function() {
    FB.init({appId: 'your app id', status: true, cookie: true,
             xfbml: true});
  };
  (function() {
    var e = document.createElement('script'); e.async = true;
    e.src = document.location.protocol +
      '//connect.facebook.net/en_US/all.js';
    document.getElementById('fb-root').appendChild(e);
  }());

即。用英语“阅读”的标准方式。 “(function(){”位是我失败的地方。我可以看到它正在做什么:运行这个位async继续并在函数()中执行操作,但是这个和什么是组件是什么?

1 个答案:

答案 0 :(得分:0)

语法有点奇怪。第一位

window.fbAsyncInit = function() {
  FB.init({appId: 'your app id', status: true, cookie: true,
           xfbml: true});
};

function expression。在其使用的上下文中,开发人员也可以写:

function fbAsyncInit() {
  FB.init({appId: 'your app id', status: true, cookie: true,
           xfbml: true});
};

请参阅this JSFiddle了解等效内容。无论哪种方式,呼叫都是相同的:

fbAsyncInit();

以下代码:

  FB.init({appId: 'your app id', status: true, cookie: true,
           xfbml: true});

调用Init对象上的FB函数并传递object literal作为参数。

这里有一点解释:

(function() {
  var e = document.createElement('script'); e.async = true;
  e.src = document.location.protocol +
    '//connect.facebook.net/en_US/all.js';
  document.getElementById('fb-root').appendChild(e);
}());

这篇文章可能有所帮助:What does this JavaScript/jQuery syntax mean?

JavaScript中的所有变量都被“提升”到全局范围,除非它们在函数中。您看到的约定是一个自动调用的匿名函数。我们本来可以写的:

function MyFunc(){
  var e = document.createElement('script'); e.async = true;
  e.src = document.location.protocol +
    '//connect.facebook.net/en_US/all.js';
  document.getElementById('fb-root').appendChild(e);
};
MyFunc();

但那可能是内存中的额外代码和额外变量。