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);
}());
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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.