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?
The syntax is a little strange. The first bit
Is a function expression. In the context of its use, the developer could also have written:
See this JSFiddle for an equivalent. Either way, calling is identical:
the following code:
Is calling the
Initfunction on theFBobject and passing an object literal as a parameter.This bit here takes a little more explanation:
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:
But that would have been extra code and extra variables in memory.