JavaScript/2주차

4. 일급 객체로서의 함수 2

tnals634 2023. 5. 23. 12:33

this는 자기자신을 가리킨다.

그래서 아래 person함수안에서 사용하는 this는 person내의 것들을 가리킨다.

즉 person.name인 this.name은 john을 가리킨다.

const person = {
    name:'john',
    age: 30,
    isMarried: true,
    sayHello:function(){
        console.log('hello, my name is ' + this.name);
    },
};

person.sayHello();

출력 : hello, my name is john

 

sayHello 부분을 화살표함수를 사용하면 아래와 같은 코드가 나오는데, 결과는 undefined가 나온다.

const person = {
    name:'john',
    age: 30,
    isMarried: true,
    //화살표 함수로 
    sayHello: () => {
        console.log(`hello, my name is ${this.name}`);
    }
};

좀 더 깊게 들어가는것은 3주차인 this를 배울때 들어간다.

지금은 간단히 말하면 화살표함수는 this를 바인딩하지 않는다. 라고 알고 있으면 됩니다.

 

 

배열의 요소로 함수를 할당

const myArr = [
    //함수가 array 형태로 들어감
    //이 두개를 요소로 갖는 배열
    function (a,b) {
        return a + b;
    }, function (a,b) {
        return a - b;
    },
];

console.log(myArr[0](1,3));
console.log(myArr[1](10,7));

이렇게 배열에 접근하듯 먼저 인덱스 부분을 지칭한 후 값을 넣어주면 된다.

출력 : 4

          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(add(multiplyByTwo(10),multiplyByThree(10)));

 

 

'JavaScript > 2주차' 카테고리의 다른 글

6. Set 소개 및 예시코드 연습  (0) 2023.05.23
5. Map 소개 및 예시코드 연습  (0) 2023.05.23
3. 일급 객체로서의 함수 1  (0) 2023.05.23
2. ES6 문법 소개 및 실습 2  (0) 2023.05.23
1. ES6 문법 소개 및 실습 1  (0) 2023.05.23