본문 바로가기
JavaScript

JavaScript 기초(24)_객체(4)

by DeBanker.K 2021. 10. 21.

1. 객체 리터럴 (Object Literal)

: '객체를 직접 써서 만든다'는 의미이다.

 

아래의 예시 코드들을 통해 알아보자.

const a = {};
console.log(a, typeof a);

const b = {
    name : 'Kim'
};
console.log(b, typeof b);
[Running]
{} object
{ name: 'Kim' } object

변수 a는 빈 객체이다. 변수 b는 name이 'Kim'인 객체이다.

두 객체 모두 중괄호로 직접 써서 객체를 만들었다.

 

위처럼 단순한 형태의 객체 말고 함수가 포함된 객체도 '직접 써서'(객체 리터럴 형태로) 아래와 같이 나타낼 수 있다.

const c = {
    name : 'Kim',
    hello1(){
        console.log('hello', this);
    },
    hello2: function(){
        console.log('hello', this);
    },
    hello3: () => {
        console.log('hello', this);
    },
};

c.hello1();
c.hello2();
c.hello3();
[Running] 
hello {
  name: 'Kim',
  hello1: [Function: hello1],
  hello2: [Function: hello2],
  hello3: [Function: hello3]
}
hello {
  name: 'Kim',
  hello1: [Function: hello1],
  hello2: [Function: hello2],
  hello3: [Function: hello3]
}
hello {}

위와 같이 3가지 방법으로 객체에 함수를 쓸 수 있다. 

다만 'hello3'처럼 화살표 함수(arrow function) 형태로 나타낸 경우에는 결과 값에서 보듯

'this'를 가지고 오지 못하기 때문에 빈 값으로 출력이 되었다.

 

구체적으로 아래와 같이 'this.name'을 대입하면 어떻게 될까? 

const c = {
    name : 'Kim',
    hello1(){
        console.log('hello', this.name);
    },
    hello2: function(){
        console.log('hello', this.name);
    },
    hello3: () => {
        console.log('hello', this.name);
    }
};

c.hello1();
c.hello2();
c.hello3();
[Running] 
hello Kim
hello Kim
hello undefined

예상했던 대로 'hello3'은 'name'을 받아오지 못해 undefined로 출력되었다.

 

오늘은 객체 리터럴에 대해서 간략하게 알아보았다. 

'JavaScript' 카테고리의 다른 글

JavaScript 기초(26)_클래스(1) constructor  (0) 2021.10.23
JavaScript 기초(25)_객체(5)  (0) 2021.10.22
JavaScript 기초(23)_객체(3)  (0) 2021.10.20
JavaScript기초(22)_객체(2)  (0) 2021.10.16
JavaScript기초(21)_객체(1)  (0) 2021.10.15

댓글