JavaScript 和 Facebook - 语法解释
我对 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 功能以及组件是什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
语法有点奇怪。第一个位
是一个函数表达式。在其使用上下文中,开发人员还可以编写:
请参阅 this JSFiddle 以获得等效内容。无论哪种方式,调用都是相同的:
以下代码:
在
FB
对象上调用Init
函数并传递 对象文字 作为参数。这里需要更多的解释:
这篇文章可能会有所帮助: JavaScript/jQuery 语法是什么意思?
JavaScript 中的所有变量都被“提升”到全局范围,除非它们位于函数中。您看到的约定是自动调用的匿名函数。我们可以写:
但这会在内存中产生额外的代码和额外的变量。
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
Init
function on theFB
object 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.