Javascript 함수선언문/표현식, 즉시실행함수

임택·2019년 4월 14일
1

Javascript

목록 보기
1/9
post-thumbnail

선언식과 호이스팅


test(); // test 출력! // Javascript Hoisting 특성 때문에 test 함수는 호출되기 전에 선언 된다.
function test() {
	console.log('test');
}

표현식1

test(); // TypeError! // test is not defined
var test = function() {
	console.log('test');
};

//위 코드는 아래와 같이 해석된다.
var test;
test();
test = function() {
	console.log('test');
}

표현식2

// 아래 코드는 함수를 반환한다.
(function test() {
	console.log('test');
})
test(); // ReferenceError! 위 코드는 표현식으로써 test() function을 반환한다. 선언하는게 아님

var test = (function test() {
	consolelog('test');
});
teat(); // test, 작동하는 이유는 (function... )이 반환한 함수를 test 변수에 할당했기 때문에 test() 호출가능

표현식과 즉시실행함수

(function test() {
	console.log('test');
})();
// test, why? (function ...) 이 코드는 함수를 f를 반환하고 f();가 실행되니까 test 출력

(function test() {
	console.log('test');
}());
// 위와 같은 동작을 수행한다.

즉시실행함수를 쓰는 이유

  • 첫 로드 시 초기화 할 때 변수를 global하게 선언하고 싶지 않을 때
  • 변수에 함수를 이용해 즉시 값을 할당하고 싶을 때
  • 라이브러리 전역 변수 충돌 방지

라이브러리 전역 변수 충돌 방지

(fucntion($) {
 // $를 충돌 없이 사용 가능
})(jQuery);
profile
캬-!

0개의 댓글