변수에 함수를 할당할 수 있다.
// const sayHello = function() {
//console.log("Hello!")
//};
함수를 인자로 다른 함수에 전달할 수가 있다.
콜백함수 : 매개변수로써 쓰이는 함수
고차함수 : 함수를 인자로 받거나 return하는 함수
function callFunction(func) {
//매개변수로 받은 변수가 사실, 함수다.
func();
}
const sayHello = function (){
console.log("Hello!")
};
callFunction(function () {
console.log("Hello!");
});
function createAdder(num) {
return function (x) {
return x + num;
};
}
const addFive = createAdder(5);
console.log(addFive(10)); //15
const person = {
name: "John",
age: 31,
isMarried: true,
sayHello: function () {
console.log(`Hello, My name is ${this.name}`);
//this 는 항상 자기 자신을 가리킨다.
//여기서 말하는 this는 person
},
};
person.sayHello();//Hello, My name is John
const person = {
name: "John",
age: 31,
isMarried: true,
sayHello:()=> {
console.log(`Hello, My name is ${this.name}`);
//this 는 항상 자기 자신을 가리킨다.
//여기서 말하는 this는 person
},
};
person.sayHello();//Hello, My name is undefined
//화살표함수는 this를 바인딩하지 않는다.
const myArr = [
function (a, b) {
return a + b;
}, //0번째 요소
function (a, b) {
return a - b;
}, // 1번째 요소
];
// 더하기
console.log(myArr[0](1, 3)); //4
// 빼기
console.log(myArr[1](10, 7)); //3
function multiplyBy(num) {
return function (x) {
return x * num;
};
}
function add(x, y) {
return x + y;
}
const multiplyByTwo = multiplyBy(2);
const multiplyByThree = multiplyBy(3);
console.log(multiplyByTwo(10)); //20
console.log(multiplyByThree(10)); //30
const result = add(multiplyByTwo(5), multiplyByThree(10));
console.log(`Final => ${result}`); //Final => 40