[英]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.