WEB/HTML+CSS+JS

[JavaScript] ν•¨μˆ˜ 정리 1-ν™”μ‚΄ν‘œν•¨μˆ˜, μ¦‰μ‹œ μ‹€ν–‰ν•¨μˆ˜(IIFE), ν˜Έμ΄μŠ€νŒ…(Hoisting)

kite707 2021. 7. 8.

기본적인 ν•¨μˆ˜ μž‘μ„±λ²•

//ν•¨μˆ˜ μ •μ˜
const double=function(x,y){
    return x*2
}
//ν•¨μˆ˜ 호좜
console.log('double :',double(7))

 

ν™”μ‚΄ν‘œ ν•¨μˆ˜

//ν•¨μˆ˜μ˜ μΆ•μ•½ν˜•
//ν™”μ‚΄ν‘œ ν•¨μˆ˜λ₯Ό μ΄μš©ν•΄ κ°„λ‹¨ν•˜κ²Œ ν•¨μˆ˜λ₯Ό μž‘μ„±ν•  수 μžˆλ‹€.

//const [ν•¨μˆ˜μ΄λ¦„] = [(ν•¨μˆ˜ 인자- ν•˜λ‚˜μ΄λ©΄ κ΄„ν˜Έ μƒλž΅κ°€λŠ₯)] => [ν•¨μˆ˜κ°€ λ°˜ν™˜ν•  λ‚΄μš©]
const doublearrow = x => x*2
console.log('doublearrow :',doublearrow(7))

//const [ν•¨μˆ˜μ΄λ¦„] = [(ν•¨μˆ˜ 인자- μ—†μœΌλ©΄ κ΄„ν˜Έ)] => [ν•¨μˆ˜κ°€ λ°˜ν™˜ν•  λ‚΄μš©]
const sh = x => ({name:'kite'})
console.log('sh :',sh(7))

 

μ¦‰μ‹œ μ‹€ν–‰ν•¨μˆ˜ (IIFE)

μ¦‰μ‹œ μ‹€ν–‰ν•¨μˆ˜
IIFE - Immediately-Invoked Function Expression
const a=14;

//방법 1 (function(){ν•¨μˆ˜λ‚΄μš©}());
(function(){
    console.log(a*2)
}());

//방법 2 (function(){ν•¨μˆ˜λ‚΄μš©})();
(function(){
    console.log(a*2)
})();

ν˜Έμ΄μŠ€νŒ…(Hoisting)

 

ν˜Έμ΄μŠ€νŒ… - ν•¨μˆ˜ μ„ μ–ΈλΆ€κ°€ μœ νš¨λ²”μœ„ μ΅œμƒλ‹¨μœΌλ‘œ λŒμ–΄μ˜¬λ €μ§€λŠ” ν˜„μƒ
둜직이 λ³΅μž‘ν•  λ•Œ μ‰½κ²Œ μ½”λ“œμ˜ 흐름을 νŒŒμ•…ν•  수 μžˆλ‹€.

const a=14;

//ν•¨μˆ˜ 선언이 λ¨Όμ € λ“±μž₯
double2()

function double2(){
    console.log(a+5)
}

λŒ“κΈ€