0

I am totally new to JavaScript and the 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);
  }());

i.e. 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?

Michael Myers
  • 188,989
  • 46
  • 291
  • 292
RichieHH
  • 2,116
  • 4
  • 28
  • 30

1 Answers1

0

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. 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.

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?

All variables in JavaScript are 'hoisted' to global scope unless they are in a function. 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.

Community
  • 1
  • 1
James Wiseman
  • 29,946
  • 17
  • 95
  • 158