[英]JavaScript and Facebook - syntax explanation
我對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(){”位是我跌倒的地方。我可以看到它在做什么:運行該位后,異步會繼續運行,並且function()中的內容也會起作用,但是JavaScript的功能是什么,組成部分是什么?
語法有點奇怪。 第一位
window.fbAsyncInit = function() {
FB.init({appId: 'your app id', status: true, cookie: true,
xfbml: true});
};
是一個函數表達式 。 就其使用而言,開發人員還可以編寫:
function fbAsyncInit() {
FB.init({appId: 'your app id', status: true, cookie: true,
xfbml: true});
};
有關等效信息,請參見此JSFiddle 。 無論哪種方式,調用都是相同的:
fbAsyncInit();
以下代碼:
FB.init({appId: 'your app id', status: true, cookie: true,
xfbml: true});
正在調用FB
對象上的Init
函數,並將對象文字作為參數傳遞。
這一點需要更多說明:
(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);
}());
本文可能會有所幫助: 此JavaScript / jQuery語法是什么意思?
除非它們在函數中,否則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();
但這將是額外的代碼和內存中的額外變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.