函数上的额外括号 [英] Extra parentheses on function
本文介绍了函数上的额外括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我遇到类似这样的标记:
I encountered markup similar to this:
var something = (function(){
//do stuff
return stuff;
})()
document.ondblclick = function(e) { alert(something(e)) };
我不明白开头(
并在 something
变量中关闭)()
。
I don't understand the opening (
and closing )()
in the something
variable.
Could you explain the difference to writing it like this?
var something = function(){
//do stuff
return stuff;
};
$ b
谢谢!
Thanks!
推荐答案
这可能更容易理解,如果你离开冗余的括号,因为他们没有目的:
It's probably easier to understand if you leave the redundant parens out because they serve no purpose:
var something = function() {
return 3;
} // <-- a function.
(); // now invoke it and the result is 3 (because the return value is 3) assigned to variable called something
console.log(something) //3 because the function returned 3
var something = function() {
return 3;
}; // a function is assigned to a variable called something
console.log(something) //logs the function body because it was assigned to a function
console.log(something()) //invoke the function assigned to something, resulting in 3 being logged to the console because that's what the function returns
这篇关于函数上的额外括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文