(function () { /* ... */ })();
(function () { /* ... */ }());
(() => { /* ... */ })();
a regular function
function () {}
+
function call
();
IIFE
- Immediately-Invoked Function Expression
- It executes immediately after it’s created.
It was popular in JavaScript as a method to support modular programming before the introduction of more standardized solutions such as CommonJS and ES modules.
Immediately invoked function expressions can be used to avoid variable hoisting from within blocks, protect against polluting the global environment and simultaneously allow public access to methods while retaining privacy for variables defined within the function.
Immediately invoked function expressions may be written in a number of different ways.
A common convention is to enclose the function expression – and optionally its invocation operator – with the grouping operator, in parentheses, to tell the parser explicitly to expect an expression. Otherwise, in most situations, when the parser encounters the function keyword, it treats it as a function declaration (statement), and not as a function expression.
[출처] WIKIPEDIA, "Immediately invoked function expression"
티스토리 블로그에 적용한 예문
$(document).ready(function() {
const indicator = document.querySelector('#nav-header h1');
indicator.append( decodeURIComponent(window.location.pathname).replace(/\//g," / ") );
});
블로그 스킨 "script.js" 파일에 있던 위의 함수식을 아래와 같이 IIFE 형식 구문을 사용하여 "skin.html" 파일의 </body> 위로 옮겼습니다.
DOM이 준비되면 바로 이 구문이 실행됩니다.
<script>
(function() {
const indicator = document.querySelector('#nav-header h1');
indicator.append( decodeURIComponent(window.location.pathname).replace(/\//g," / ") );
})();
</script>
</body>
</html>
[참고] stackoverflow,
- "What is the (function() { } )() construct in JavaScript?",
- "$(document).ready equivalent without jQuery"
댓글