简体   繁体   English

JavaScript和Facebook-语法说明

[英]JavaScript and Facebook - syntax explanation

I am totally new to JavaScript and the Facebook SDK. 我对JavaScript和Facebook SDK完全陌生。 Could someone describe in English the following feature: 有人可以用英语描述以下功能:

  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);
  }());

ie the standard way of "reading" this in English. 即用英语“阅读”此内容的标准方式。 The "(function (){" bit is where I fall over. I can see what it's doing: after running this bit async goes on and does the stuff in function(), but what JavaScript feature is this and what are the components? “(function(){”位是我跌倒的地方。我可以看到它在做什么:运行该位后,异步会继续运行,并且function()中的内容也会起作用,但是JavaScript的功能是什么,组成部分是什么?

The syntax is a little strange. 语法有点奇怪。 The first bit 第一位

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

Is a function expression . 是一个函数表达式 In the context of its use, the developer could also have written: 就其使用而言,开发人员还可以编写:

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

See this JSFiddle for an equivalent. 有关等效信息,请参见此JSFiddle Either way, calling is identical: 无论哪种方式,调用都是相同的:

fbAsyncInit();

the following code: 以下代码:

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

Is calling the Init function on the FB object and passing an object literal as a parameter. 正在调用FB对象上的Init函数,并将对象文字作为参数传递。

This bit here takes a little more explanation: 这一点需要更多说明:

(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);
}());

This article might help: What does this JavaScript/jQuery syntax mean? 本文可能会有所帮助: 此JavaScript / jQuery语法是什么意思?

All variables in JavaScript are 'hoisted' to global scope unless they are in a function. 除非它们在函数中,否则JavaScript中的所有变量都“提升”到全局范围。 The convention you see is an anonymous function that is automatically invoked. 您看到的约定是自动调用的匿名函数。 We could have written: 我们可以写:

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();

But that would have been extra code and extra variables in memory. 但这将是额外的代码和内存中的额外变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM