这个问题在这里已经有一个答案:
JavaScript中的(function(){}()构造是什么? 18答案我正在尝试阅读原型源。 我来到这个部分(不幸的是,这段代码是在开始的)。
这是什么意思?
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) } })(),我是指逗号前的最后一行吗?
This question already has an answer here:
What is the (function() { } )() construct in JavaScript? 22 answersI'm trying to read the Prototype source. I've come to this part.(Unfortunately, this snippet is in the beginnning).
What does this () mean?
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属性。
您还可以在某处定义功能:
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, ...这样做的一个缺点是,你用一个函数和一个变量来“污染你的命名空间”,你不会在别的地方使用。 第二个问题是您不能在函数定义中使用任何本地范围变量的值(匿名函数作为闭包)。
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) }and then call it:
var foo = myFunction();and then assign the value:
... 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).
更多推荐
发布评论