问题描述
我正在尝试阅读Prototype源代码。我来到这一部分。(不幸的是,这个片段在开头)。
I'm trying to read the Prototype source. I've come to this part.(Unfortunately, this snippet is in the beginnning).
这是什么意思?
Browser: (function(){
var ua = navigator.userAgent;
var isOpera = Object.prototype.toString.call(window.opera) == '[object Opera]';
return {
IE: !!window.attachEvent && !isOpera,
Opera: isOpera,
WebKit: ua.indexOf('AppleWebKit/') > -1,
Gecko: ua.indexOf('Gecko') > -1 && ua.indexOf('KHTML') === -1,
MobileSafari: /Apple.*Mobile.*Safari/.test(ua)
}
})(),
我指的是逗号前的最后一行?
I am referring to the last line before the comma?
推荐答案
代码正在定义一个匿名函数((function(){...})
位),然后调用它(没有参数)。然后,它将值分配给对象的 Browser
属性,该属性可能是在代码片段之外定义的。
The code is defining an anonymous function (the (function (){ ... })
bit) and then calling it (with no arguments). It then assigns the value to the Browser
property of the object that is presumably being defined outside of your code snippet.
您还可以在某处定义函数:
You could also define the function somewhere:
function myFunction() {
var ua = navigator.userAgent;
var isOpera = Object.prototype.toString.call(window.opera) == '[object Opera]';
return {
IE: !!window.attachEvent && !isOpera,
Opera: isOpera,
WebKit: ua.indexOf('AppleWebKit/') > -1,
Gecko: ua.indexOf('Gecko') > -1 && ua.indexOf('KHTML') === -1,
MobileSafari: /Apple.*Mobile.*Safari/.test(ua)
}
然后调用它:
var foo = myFunction();
然后分配价值:
...
Browser: foo,
...
这样做的一个缺点是你用一个你不会在其他地方使用的函数和变量来污染你的命名空间。第二个问题是您不能在函数定义中使用任何本地范围的变量的值(匿名函数表现为闭包)。
One downside with doing it that way is that you "pollute your namespace" with a function and a variable that you won't use anywhere else. The second issue is that you can't use the value of any locally-scoped variables in your function definition (the anonymous function behaves as a closure).
这篇关于函数声明后在javascript中做空括号()是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!