function sayHi(name){...} // name => 매개변수sayHi("Taemin"); // 매개변수 name에 대해서 'Taemin'은 함수의 인수이다.addEventListener : 브라우저가 정의한 함수. JavaScript가 생성한 객체이다.
메서드 : 객에체 함수가 저장된 것.
const person = {
name: "Max",
greet: function greet() {
console.log("Hello");
},
};
person.greet(); // Hello
function startGame() {
console.log("Game is starting...");
}
console.dir(startGame);
//ƒ startGame()
//arguments: null
//caller: null
//length: 0
//name: "startGame"
//prototype: {constructor: ƒ}
//[[FunctionLocation]]: app.js:3
//[[Prototype]]: ƒ ()
//[[Scopes]]: Scopes[2]
//0: Script {startGameBtn: button#start-game-btn}
//1: Global {window: Window, self: Window, document: document, name: '', location: Location, …}
const start = function startGame() {
console.log("Game is starting...");
};
해당 함수는 startGame이라는 이름으로 스코프에 저장되지 않음. 그 대신 start로 저장된다.
const start = function () {
console.log("Game is starting...");
};
함수 선언(Function Declaration / Function Statement)
function multiply(a, b) {
return a * b;
}
=> JavaScript가 자동으로 함수를 맨 위로 Hoist 함. 그리고 완전히 초기화함.
함수 표현식(Function Expression)
const multiply = function (a, b) {
return a * b;
};
=> 상수가 정의되지 않은 상태로 호이스트됨. 따라서 파일의 어디에서나 선언될 수는 없다.
startGameBtn.addEventListener("click", function () {
console.log("Game is starting...");
});
// 하지만 익명함수를 쓰면 나중에 디버깅할 때 함수 이름을 알기가 힘들다.
const getWinner = (cChoice, pChoice) => {
if (cChoice === pChoice) {
return RESULT_DRAW;
} else if (
(cChoice === ROCK && pChoice === PAPER) ||
(cChoice === PAPER && pChoice === SCISSORS) ||
(cChoice === SCISSORS && pChoice === ROCK)
) {
return RESULT_PLAYER_WINS;
} else {
return RESULT_COMPUTER_WINS;
}
};
// 다음과 같이 작성할 수 있다.
const getWinner = (cChoice, pChoice) =>
cChoice === pChoice
? RESULT_DRAW
: (cChoice === ROCK && pChoice === PAPER) ||
(cChoice === PAPER && pChoice === SCISSORS) ||
(cChoice === SCISSORS && pChoice === ROCK)
? RESULT_PLAYER_WINS
: RESULT_COMPUTER_WINS;
// 일반적으로 다음과 같이 작성한다.
(arg1, arg2) => {...}
// 1. No Arguments / Parameters
() => {...}
// 2. 하나의 Argument / Parameter가 있는 경우
arg => {...}
// 3. Exactly one expression in function body
(a, b)=> a + b
// 4. More than one expression in function body
(a, b) => {
a *= 2;
return a + b;
}
undefined일 때만 반영이 됨(혹은 값이 전달되지 않았거나). 다른 falsy 값은 영향을 미치지 않게 된다.const getWinner = (cChoice, pChoice = DEFAULT_USER_CHOICE) => {...}
// 참고 : 이런식으로 작성해도 됨
const getWinner = (cChoice, pChoice = cChoice === 'ROCK' ? PAPER : DEFAULT_USER_CHOICE)=>{...}
const sumUp = (...numbers) => {
let sum = 0;
for (const num of numbers) {
sum += num;
}
return sum;
};
const subtractUp = function () {
let sub = 0;
for (const num of arguments) {
// arguments는 JavaScript에서 이미 설계된 것. function 키워드를 사용하는 함수 안에서만 사용이 가능하다.
// 하지만 Rest 매개변수를 사용하는 방법을 써라!
sub -= num;
}
return sub;
};
console.log(sumUp(1, 5, 10, -3, 6, 10));
console.log(sumUp(1, 5, 10, -3, 6, 10, 25, 80));
console.log(subtractUp(1, 10, 15, 20));
const sumUp = (...numbers) => {
const validateNumber = (number) => {
return isNaN(number) ? 0 : number;
};
let sum = 0;
for (const num of numbers) {
sum += validateNumber(num);
}
return sum;
};
console.log(sumUp(1, 5, 10, -3, 6, 10));
console.log(sumUp(1, 5, 10, -3, 6, 10, 25, 80));
const sumUp = (resultHandler, ...numbers) => {
const validateNumber = (number) => {
return isNaN(number) ? 0 : number;
};
let sum = 0;
for (const num of numbers) {
sum += validateNumber(num);
}
resultHandler(sum);
};
const showResult = (result) => {
alert("The result after adding all numbers is: " + result);
};
sumUp(showResult, 1, 5, 10, -3, 6, 10);
sumUp(showResult, 1, 5, 10, -3, 6, 10, 25, 80);
bind() 사용하기const combine = (resultHandler, operation, ...numbers) => {
const validateNumber = (number) => {
return isNaN(number) ? 0 : number;
};
let sum = 0;
for (const num of numbers) {
if (operation === "ADD") {
sum += validateNumber(num);
} else {
sum -= validateNumber(num);
}
}
resultHandler(sum);
};
// const subtractUp = function (resultHandler, ...numbers) {
// let sub = 0;
// for (const num of numbers) {
// sub -= num;
// }
// resultHandler(sub, 'The result after subtracting all numbers is');
// };
const showResult = (messageText, result) => {
alert(messageText + " " + result);
};
combine(
showResult.bind(this, "The result after adding all numbers is:"),
"ADD",
1,
5,
10,
-3,
6,
10
);
combine(
showResult.bind(this, "The result after adding all numbers is:"),
"ADD",
1,
5,
10,
-3,
6,
10,
25,
80
);
combine(
showResult.bind(this, "The result after subtracting all numbers is:"),
"SUBTRACT",
1,
10,
15,
20
);