본문 바로가기

프로그래밍/JAVASCRIPT

JS 함수 괄호 () 사용 여부

1
2
3
4
5
6
7
8
9
<script type="text/javascript">
    window.onload = function() {
        setInterval(a, 1000);
    };
    
    function a() {
        console.log("123");
    }
</script>
cs
1
2
3
4
5
6
7
8
9
<script type="text/javascript">
    window.onload = function() {
        setInterval(a(), 1000);
    };
    
    function a() {
        console.log("123");
    }
</script>
cs

위 코드는 1초 뒤에 a함수를 실행하지만, 

아래 코드는 바로 a함수가 실행되고 오류를 반환한다.

 

이는 콘솔에 찍어보면 쉽게 이해할 수 있다.

()가 붙는 순간 자바스크립트는 함수를 실행한다. 

하지만 없다면 그건 함수의 레퍼런스를 뜻한다.

저기서 괄호를 넣어주지 않는 이유는 저 코드가 읽히면서 함수를 실행하는 것을 바라는 것이 아니기 때문이다.

자바스크립트에서는 함수도 객체로 취급된다. 

함수의 레퍼런스를 받고 나중에 호출해야 할 때, 함수를 따로 호출하는 방식을 취한다.

 

때문에 아래 setInterval함수의 첫번째 인수에 a()를 넘겨주면 그 리턴 값이 들어가게 되는 것이고, a를 넘겨주면, a함수의 레퍼런스가 들어가게 되는 것이다. 

콘솔로 보면 쉽게 이해할 수 있다. 

 

아래 글을 참고했다.

https://teamtreehouse.com/community/why-do-we-call-the-functions-without-parentheses-ie#:~:text=A%20function%20name%20without%20the,where%20that%20code%20is%20encountered.

 

Why do we call the functions without parentheses i.e. '()'? (Example) | Treehouse Community

We created two functions: passwordEvent() and confirmPasswordEvent(). Normally when you call a function, you have to include parentheses like w...

teamtreehouse.com

'프로그래밍 > JAVASCRIPT' 카테고리의 다른 글

JS weather api, fetch api  (0) 2022.06.02