(…()) vs. (…)() in javascript closures
This question already has an answer here:
I know this is silly, but there's any difference between this:
(function() {
var foo = 'bar';
})();
and this?
(function() {
var foo = 'bar';
}());
JSLint tells us to Move the invocation into the parens that contain the function
, but I see no need to.
Edit: The answers are too cool. ~function
, the JSHint alternative along with jQuery's preference for (/***/)();
and Crockford's explanation! I thought I was going to just get a "they're the same thing" kind of answer.
You guys decide the best one through upvotes and I tick it.
There's no difference. Both are valid ways to get the JavaScript parser to treat your function as an expression instead of a declaration.
Note that +
and !
will also work, and are sometimes used by minifiers to save a character of size:
+function() {
var foo = 'bar';
}();
!function() {
var foo = 'bar';
}();
EDIT
As @copy points out, for completeness, ~
and -
will also work.
-function() {
var foo = 'bar';
}();
~function() {
var foo = 'bar';
}();
That JSLint violation exists because Douglas Crockford says that the outside-parentheses version looks like "dog balls".
You can hear him discuss it in this video:
I think that looks goofy, 'cause what we're talking about is the whole invocation, but we got these things hanging outside of it looking sorta like ... dog balls.
He suggests that the parentheses inside help the reader understand that the entire statement is a function expression rather than a declaration.
No, I don't believe there's any difference. I personally prefer the former (and jQuery et. al. seem to agree) but they both work identically in every engine I've tested.
Also, JSLint is a little too strict sometimes. JSHint might be a little better in that regard.
참고URL : https://stackoverflow.com/questions/8774425/vs-in-javascript-closures
'UFO ET IT' 카테고리의 다른 글
cmake 변수 범위, add_subdirectory (0) | 2020.11.24 |
---|---|
액세스 토큰없이 Facebook Graph API를 사용하여 공개 페이지 상태 가져 오기 (0) | 2020.11.24 |
JSLint가 "var 문이 너무 많다"고 말하는 이유는 무엇입니까? (0) | 2020.11.23 |
다중 처리 오류와의 또 다른 혼동, '모듈'개체에 'f'속성이 없습니다. (0) | 2020.11.23 |
인덱스 키 열 VS 인덱스 포함 열 (0) | 2020.11.23 |