๊ตฌ์ฑ์์
1. ํจ์์ ์ด๋ฆ (์๋ณ์)
2. ๊ดํธ ์์ ์ผํ(,)๋ก ๊ตฌ๋ถ๋๋ ํจ์์ ๋งค๊ฐ๋ณ์(parameter)
๋งค๊ฐ๋ณ์(parameter)๋ ํจ์๋ฅผ ํธ์ถํ ๋ ์ธ์(argument)๋ก ์ ๋ฌ๋ ๊ฐ์
ํจ์ ๋ด๋ถ์์ ์ฌ์ฉํ ์ ์๊ฒ ํด์ฃผ๋ ๋ณ์์ด๋ค
3. ์ค๊ดํธ({})๋ก ๋๋ฌ์ธ์ธ ์๋ฐ์คํฌ๋ฆฝํธ ์คํ๋ฌธ
๋ฌธ๋ฒ
function ํจ์์ด๋ฆ(๋งค๊ฐ๋ณ์1, ๋งค๊ฐ๋ณ์2,...)
{
ํจ์๊ฐ ํธ์ถ๋์์ ๋ ์คํํ๊ณ ์ ํ๋ ์คํ๋ฌธ;
}
๋ฐํ๋ฌธ return ์ฌ์ฉ๊ฐ๋ฅ
ํจ์๋ฅผ ์ค์ง์ํค๊ณ ํด๋น ๊ฐ์ ํธ์ถ์์๊ฒ ๋ฐํ
๋ฐํ๋ฌธ์ ๋ฐฐ์ด์ด๋ ๊ฐ์ฒด๋ฅผ ํฌํจํ ๋ชจ๋ ํ์
์ ๊ฐ์ ๋ฐํํ ์ ์๋ค
์๋ฐ์คํฌ๋ฆฝํธ์์ ํจ์๋ ๋ฌธ๋ฒ์ ๊ตฌ๋ฌธ์ผ๋ฟ๋ง ์๋๋ผ ๊ฐ(value)์ด๊ธฐ๋ ํ๋ค
๋ฐ๋ผ์ ํจ์๊ฐ ๋ณ์์ ๋์
๋ ์๋ ์์ผ๋ฉฐ, ๋ค๋ฅธ ํจ์์ ์ธ์๋ก ์ ๋ฌ๋ ์๋ ์๋ค
const creature = "Common Sea Dragon";
function scubaDive()
{
const creature = "Spanish Dancer";
console.log(creature);
}
scubaDive();
+) 1. scubaDive ํจ์๋ฅผ ํธ์ถํ์ ๋ฟ ํจ์ ๋ฐ๊นฅ๊ณผ ์์ ๋ณ๊ฐ์ด๋ค
๋๋ฌธ์ console.log(creature)๋ ํจ์ ๋ด๋ถ์ ์ ์์ ์ํฅ์ ๋ฐ๊ณ
์ถ๋ ฅ๊ฐ์ "Spanish Dancer"๊ฐ ๋๋ค
2. ๋ํ ํจ์ ๋ด๋ถ์์ ์ ์๋ ๊ฐ์ ๋น์ฐํ๊ฒ๋ ํจ์ ๋ด๋ถ์์๋ง ์ ์ฉ๋๋ค ๋๋ฌธ์ scubaDive() ๋ฐ๋ก ์์ค์ creature๋ฅผ ์ถ๋ ฅํ๊ฒ ๋๋ฉด ์ถ๋ ฅ๊ฐ์ "Common Sea Dragon"์ด ๋๋ค
for(let i =0;i<5;i++)
{
let msg = "ASD";
console.log(msg);
}
console.log(msg);
+)msg๋ณ์๋ let์ผ๋ก ์ ์ธ๋์ด for๋ฌธ ์์์๋ง ์ ์ฉ๋๋ค
๋๋ฌธ์ for๋ฌธ ๋ฐ๊นฅ์ ์๋ msg ๋ณ์๋ด์ฉ์ ์ถ๋ ฅ๋์ง ์๋๋ค
for(let i =0;i<5;i++)
{
var msg = "ASD";
console.log(msg);
}
console.log(msg);
+)msg๋ณ์๋ var๋ก ์ ์ธ๋์ด for๋ฌธ ๋ฐ์์๋ ์ ์ฉ๋๋ค
๋๋ฌธ์ for๋ฌธ ๋ฐ๊นฅ์ ์๋ msg ๋ณ์๋ด์ฉ์ ์ถ๋ ฅ๋๋ค
์ด๋ฐ ์ฐจ์ด์ ์ผ๋ก ์ธํ ์ค๋ฅ ๋ฐ์ ์ฌ์ง๋๋ฌธ์ var์ฌ์ฉ์ ์ง์ํ๋ ๊ฒ์ด๋ค
ํจ์๋ฅผ ๋ณ์๋ก ์ง์ ํ ์ ์๋ค
ex) const add = function(x,y)
{
return x+y;
}
input add(x,y)
๊ณ ์ฐจ ํจ์
function callTwice(func){
func();
func();
}
function rollDie(){
const roll = Math.floor(Math.random() *6) +1
console.log(roll)
}
callTwice(rollDie)
๋ฐํ ํจ์
ํจ์์์ return ๊ฐ์ผ๋ก ํจ์๋ฅผ ํธ์ถํ๋ ๊ฒ
๋ฉ์๋๋ ๊ฐ์ฒด์ ์ข
์๋ ํน์ฑ์ผ๋ก ํจ์์ ํฌํจ๋๋ ๊ฐ๋
๋ชจ๋ ๋ฉ์๋๋ ํจ์์ด์ง๋ง ๋ชจ๋ ํจ์๊ฐ ๋ฉ์๋ ์ธ๊ฒ์ ์๋๋ค
method์ ์ธ (์ค๊ดํธ,์ผํ(,),์ฝ๋ก (:)) ์ฌ์ฉ
ex) const myMath = {
PI : 3.14159,
square(num) {
return num*num;
},
cube(num) {
return num ** 3;
}
}
ํธ์ถ
myMath.cube(2)
this์ ๊ฐ์ ํจ์๋ฅผ ํธ์ถํ๋ ๋ฐฉ๋ฒ์ ์ํด ๊ฒฐ์ ๋๋ค
this ํค์๋๋ ์ฌ์ฉ ๋ฐฉ๋ฒ์ ๋ฐ๋ผ ๋ค๋ฅธ ๊ฐ์ฒด๋ฅผ ์ฐธ์กฐํ๋ค
1. ๊ฐ์ฒด๋ฉ์๋์์๋ this๊ฐ ๊ฐ์ฒด๋ฅผ ์ฐธ์กฐ
2. ๋จ๋
์ผ๋ก ์ฐ์ผ ๋, this๊ฐ ์ ์ญ ๊ฐ์ฒด๋ฅผ ๋ํ๋
3. ํจ์์์๋ this๊ฐ ์ ์ญ ๊ฐ์ฒด๋ฅผ ๋ํ๋
์ผ๋จ์ ์ด ์ ๋๋ง ์ง๊ณ ๋ค์์ ๋์์ค์
์์ธํ ๋ด์ฉ์ ์ค๋ช ์ด ์๋์ด ์๋ ์ด ๊ณณ์ ์ฐธ์กฐ https://velog.io/@harimad/JavaScript%EC%97%90%EC%84%9C-this-%ED%82%A4%EC%9B%8C%EB%93%9C%EB%9E%80
try {
์์ธ๋ฅผ ์ฒ๋ฆฌํ๊ธธ ์ํ๋ ์คํ ์ฝ๋;
} catch (ex) {
์์ธ๊ฐ ๋ฐ์ํ ๊ฒฝ์ฐ์ ์คํ๋ ์ฝ๋;
} finally {
try ๋ธ๋ก์ด ์ข
๋ฃ๋๋ฉด ๋ฌด์กฐ๊ฑด ์คํ๋ ์ฝ๋;
}
try ๋ธ๋ก = ํ์
catch,finally ๋ธ๋ก = ์ ํ
throw - ์์ธ๋ฅผ ๋ฐ์์ํค๋ ํค์๋์ด๋ค
ํํ์์๋ ์์ธ ์ฝ๋๋ฅผ ๋ํ๋ด๋ ์ซ์(Number)๋ ์ค๋ฅ ๋ฉ์์ง๋ฅผ ๋ด๊ณ ์๋ ๋ฌธ์์ด(String),
Error ๊ฐ์ฒด(Object) ๋ฑ์ด ์ฌ ์ ์๋ค.