JavaScript
일급 객체로서의 함수(2)
무녀누
2024. 4. 23. 14:44
저번에 이어서 이번에는
person에 대한 객체를 만들어보겠다.
const person = {
name: "moon",
age: 25,
isMarried: true,
sayhello: function () {
console.log("hello my name is => " + this.name)
}
};
person.sayhello();
이렇게 작성하고 실행하면 console.log가 정상적으로 실행된다.
전에 배웠던 ``를 응용해 보자.
const person = {
name: "moon",
age: 25,
isMarried: true,
sayhello: function () {
console.log(`hello my name is ${this.name}`);
}
};
person.sayhello();
이렇게 변경할 수 있다.
여기서 또 전에 배웠던 화살표 함수로 변경을 해보면
const person = {
name: "moon",
age: 25,
isMarried: true,
sayhello: () => console.log(`hello my name is ${this.name}`)
};
person.sayhello();
이렇게 더 간단하게 코드를 작성할 수 있다.
하지만 화살표함수로 작성했을 때
기존과 다른 문제점이 발생했다.
출력을 했을 때 화살표함수로 변경 전에는 this.name
즉 객체의 key값을 잘 가져와서 moon을 출력했지만
화살표함수로 변경한 후에는 undefined로 바뀌었다.
왜 이렇게 된 건지는 나중에 this를 자세히 공부할 때 알아보겠다.
간단하게라도 알아보면 화살표 함수는 this를 바인딩하지 않는다고 한다.
그래서 undefined로 출력하나 보다.
배열의 요소로 함수를 할당
먼저 배열을 생성해 보겠다.
예시
const myArr = [
function (a, b) {
return a + b;
},
function (a, b) {
return a - b;
}
];
console.log(myArr[0](2,2));
이렇게 배열을 생성했는데 기존 배열과는 다르게
배열 안에 함수를 생성했다.
호출하는 방법은
console에도 나와있듯이 배열은 0부터 시작하니
배열명[배열 순서](매개변수) 이렇게 작성하면
속성 순서에 맞는 함수를 호출해서 실행한다.
저 console.log의 출력값은 0번째 함수로 들어가서 더하기를 하니
출력값은 4가 된다.
연습 예시
function multiplyBy(num) {
return function (x) {
return x * num;
};
}
function add(x, y) {
return x + y;
}
const multiplyByTwo = multiplyBy(2);
//const multiplyByTwo = function (x) {
// return x * 2;
//};
const multiplyByThree = multiplyBy(5);
console.log(multiplyByTwo(2));
console.log(multiplyByThree(3));
const result = add(multiplyByTwo(2), multiplyByThree(3));
console.log(`finally => ${result}`);
이렇게 작성을 하면
출력값이 어떻게 나올까?
먼저 코드를 살펴보면
multiplyBy함수에 리턴값으로 다시 함수가 들어가 있다.
그 함수는 각각 num, x 매개변수의 값을 곱하는 함수이고
밑에 함수는 x, y라는 매개변수의 값을 서로 더해서 리턴하는 함수이다.