[Javascript] 객체 리터럴(object literal)

nxnaxx·2021년 11월 11일
7

javascript

목록 보기
6/14
post-thumbnail

객체(object)

 자바스크립트는 객체 기반 프로그래밍 언어이며, 원시 값을 제외한 나머지 값은 모두 객체이다.

객체는 0개 이상의 프로퍼티로 구성된 집합으로, 프로퍼티는 keyvalue로 구성된다.

프로퍼티 값이 함수일 경우에는 method라 부른다.

📝 프로퍼티와 메서드

프로퍼티(property) : 객체의 상태를 나타내는 값
메서드(method) : 프로퍼티를 참조하고 조작할 수 있는 동작


객체 리터럴(object literal)

 리터럴은 사람이 이해할 수 있는 문자나 약속된 기호를 사용해 값을 생성하는 표기법을 말하는데, 자바스크립트에서 객체를 생성하는 가장 일반적인 방법이 객체 리터럴을 사용하는 것이다.

객체 리터럴은 중괄호({}) 내에 0개 이상의 프로퍼티를 정의한다.

// object literal
var me = {
  name : 'Kim',
  intro : function() {
    console.log(`My name is ${this.name}`);
  }
};

console.log(typeof me);
console.log(me);

[실행결과]
object
{ name: 'Kim', intro: [Function: intro] }

📌 객체 리터럴의 중괄호는 코드 블록을 의미하는 것이 아니라 값으로 평가되기 때문에 닫는 괄호 뒤에는 세미콜론(;)을 붙인다.


프로퍼티(property)

 프로퍼티를 나열할 때는 쉼표(,)로 구분한다.

var me = {
  name : 'Kim',
  age : 23
};

프로퍼티 키(key) : 빈 문자열 포함 모든 string 또는 symbol 값
프로퍼티 값(value) : 자바스크립트에서 사용할 수 있는 모든 값


프로퍼티 키는 프로퍼티 값에 접근할 수 있는 이름으로서 식별자 역할을 하는데, 식별자 네이밍 규칙을 준수한다면 따옴표를 생략할 수 있으나 그렇지 않은 경우 반드시 따옴표''를 사용해야 한다. (가급적이면 식별자 네이밍 규칙을 따르는 프로퍼티 키를 사용하는 것이 좋다.)

또한 이미 존재하는 프로퍼티 키를 중복 선언하면 나중에 선언한 프로퍼티가 이전의 것을 덮어쓰며 에러도 발생하지 않는다.

var me = {
  name : 'Kim',
  name : 'Yoo'
};

console.log(me);

[실행결과]
Yoo

메서드(method)

 자바스크립트의 함수는 객체라서 값으로 취급할 수 있기 때문에 프로퍼티 값으로도 사용할 수 있다.

// method
var square = {
  side: 4, // 한 변의 길이

  getArea: function() { // 사각형 넓이 구하는 함수
    return this.side * this.side; // this는 객체 자신을 가리키는 참조 변수
  }
};

console.log(square.getArea());

[실행결과]
16

프로퍼티 접근

 프로퍼티에 접근하는 방법은 2가지가 있다.

마침표 표기법(dot notation) : 마침표 프로퍼티 접근 연산자(.) 사용
대괄호 표기법(bracket notation) : 대괄호 프로퍼티 접근 연산자([ ]) 사용

var me = {
  name: 'Kim'
};

// dot notation
console.log(me.name);

// bracket notation
console.log(me['name']);

// not exist
console.log(me.birth);

[실행결과]
Kim
Kim
undefined

📌 대괄호 표기법을 사용할 때는 접근 연산자 내부에 지정하는 프로퍼티 키는 반드시 따옴표로 감싼 문자열이어야 한다.
객체에 존재하지 않는 프로퍼티에 접근하면 undefined를 반환한다.


프로퍼티 값 갱신

 이미 존재하는 프로퍼티에 값을 할당하면 프로퍼티 값이 갱신된다.

// update property
var myFavorite = {
  sport: 'futsal',
  instrument: 'guitar',
  game: 'The Legend of Zelda'
};

myFavorite.instrument = 'piano';

console.log(myFavorite);

[실행결과]
{ sport: 'futsal', instrument: 'piano', game: 'The Legend of Zelda' }

프로퍼티 동적 생성

 존재하지 않는 프로퍼티에 값을 할당하면 동적으로 생성되어 추가된다.

// dynamic property
var myFavorite = {
  sport: 'futsal',
  instrument: 'guitar',
  game: 'The Legend of Zelda'
};

myFavorite.fruit = 'lemon';

console.log(myFavorite);

[실행결과]
{
  sport: 'futsal',
  instrument: 'guitar',
  game: 'The Legend of Zelda',
  fruit: 'lemon'
}

프로퍼티 삭제

 delete 연산자를 사용하면 객체의 프로퍼티를 삭제할 수 있다.

// dynamic property
var myFavorite = {
  sport: 'futsal',
  instrument: 'guitar',
  game: 'The Legend of Zelda'
};

delete myFavorite.game;

console.log(myFavorite);

[실행결과]
{ sport: 'futsal', instrument: 'guitar' }

13개의 댓글

comment-user-thumbnail
2023년 1월 13일

This is such a great post! It’s the little things in life that mean the most and make up the larger moments in our lives! https://run3game.io

답글 달기
comment-user-thumbnail
2023년 4월 5일

This is such a great post!
Pelle Pelle Soda Club Classic Jacket

답글 달기
comment-user-thumbnail
2023년 5월 26일

I have been looking for this information for a long time, I was very surprised when I found it here.
New Pelle Pelle

답글 달기
comment-user-thumbnail
2023년 6월 13일

I have been looking for this information for a long time, I was very surprised when I found it here. https://celebrityjackets.us/

답글 달기
comment-user-thumbnail
2023년 6월 19일
답글 달기
comment-user-thumbnail
2023년 8월 29일

We travelled around the world to learn the history of leather jackets or sheepskin apparel that used to be worn in ancient times. As we got to know its real essence, we got inspired to start up our own company called American Jacket Store which can differ in quality and manufacturing.
What more inspired us was how they used to stitch up the best leather jackets so eloquently that the fabric did not tear apart for years. In the 1900’s it was first introduced to the market of fashion and from that time it has been on the charts as a wonderful fashion statement.
We focus on bringing that traditional quality with modern trends as a fusion so people know the real worth of this upper-layered apparel. The variety is filled with different categories like leather biker jackets, bomber jackets, leather coats, and much more. The finest and best leather jackets from the American jackets store will not disappoint a jacket enthusiast.

https://www.americanjacket.store/

답글 달기
comment-user-thumbnail
2023년 9월 7일

Such an Informative Blog! I love this one. Great Work by Admin Keep it up. Please take some time to visit my website. The Best Marketplace for street wear Cloths.
https://playboygermany.co/

답글 달기
comment-user-thumbnail
2023년 9월 7일

Great Work by Admin Keep it up. Please take some time to visit my website. The Best Marketplace for street wear Cloths.
https://brokenplanethoodie.com/

답글 달기
comment-user-thumbnail
2023년 10월 2일

Great website you have got here. Keep up the good work and thanks for sharing your blog site it really helps a lot. https://theweekndmerch.co

답글 달기
comment-user-thumbnail
2023년 10월 2일

Continue to send in more valuable and astonishing information on your blog so that we enjoy it. https://badbunnymerchofficial.com

답글 달기
comment-user-thumbnail
2023년 10월 2일

Actually quite glad to say, your post is extremely fascinating to read. https://commedesgarconstore.com/

1개의 답글
comment-user-thumbnail
약 15시간 전

so helpful article, thanks so muc for sharing this with thw world... https://mrcollegehub.com

답글 달기