[JavaScript] 객체 생성, 추가, 값 가져오기

liinyeye·2024년 4월 26일

[TIL]

목록 보기
7/10

객체란?

객체란 key-value pair
객체는 관련된 데이터와 함수의 집합이다. 하나의 변수에 여러 개의 타입의 값을 넣을 수 있다.

const person = {
  name: ["Bob", "Smith"],
  age: 32,
  gender: "male",
  interests: ["music", "skiing"],
  bio: function () {
    alert(
      this.name[0] +
        " " +
        this.name[1] +
        " is " +
        this.age +
        " years old. He likes " +
        this.interests[0] +
        " and " +
        this.interests[1] +
        ".",
    );
  },
  greeting: function () {
    alert("Hi! I'm " + this.name[0] + ".");
  },
};

객체 구성 문법

var objectName = {
  member1Name: member1Value,
  member2Name: member2Value,
  member3Name: member3Value,
};

객체를 구성하는 멤버의 값은 어떤 것이라도 될 수 있다. 위의 person 객체는 문자열, 숫자, 배열 두 개와 두 개의 함수를 가지고 있다. 처음 4개의 아이템은 데이터 아이템으로, 이걸 객체의 프로퍼티(속성) 이라고 부른다. 끝에 두 개의 아이템은 함수인데 이 함수를 통해 데이터를 가지고 뭔가 일을 할 수 있게 되며, 이걸 메소드 라고 부른다.

이런 객체는 객체 리터럴(object literal)이라고 부르며, 객체를 생성할 때 콘텐츠를 그대로 대입한다.

객체 안에 있는 메소드에서 this 키워드는 지금 동작하고 있는 코드를 가지고 있는 객체를 가리킨다. 위에서 this 는 person 객체와 동일하다.

1. 객체 생성 방법

1-1. 기본적인 객체 생성

let person = {
    name : '홍길동',
    age : 20,
    gender : '남자',
};

값에는 모든 자료형이 들어갈 수 있으며 함수와 배열도 들어갈 수 있다.

const person = {
    name : '홍길동',
    age : 20,
    gender : '남자',
    interests : ['music', 'skiing'],
    greeting : function() {
    	alert('hello');
    },
  	 "is tall": true
};

1-2. 생성자 함수를 이용한 객체 생성

function Person(name, age, gender) {
    this.name = name;
    this.age = age;
    this.gender = gender;
}

let person1 = new Person("홍길동", 30, "남자");
let person2 = new Person("홍길순", 40, "여자");
console.log(person1.name); // 홍길동

생성자 함수란 new 키워드와 함께 객체를 생성하고 초기화 하는 함수를 말한다. 생성자 함수를 통해 생성된 객체를 인스턴스(instance)라고 한다. 생성자 함수를 사용하면 객체를 일괄적으로 생성할 수 있다.

여기서 생성자 함수 Person이 가리키는 this값은 new 연산자로 생성된 인스턴스를 가리킨다. 따라서 this는 새로 생성한 객체로 반환된 인스턴스인 person1 과 person2가 되고 인자로 전달받은 값이 생성된 객체 프로퍼티의 값으로 할당된다.

1-3. 빈 객체 생성

const person = {};
const person = new Object();

객체 person을 생성한 이후 새 속성을 추가할 때 '점 표기법'을 사용한다.

person.name = 'Bob';

대괄호 표기법으로도 객체에 새 속성을 추가할 수 있다.

person['name'] = 'Bob';

2. 객체 값 가져오기

객체 속성에 접근할 때 점 표기법과 괄호 표기법으로 접근할 수 있다.

(1) 점 표기법

console.log("1.", person.name); // 1. 홍길동
console.log("2.", person.age); // 2. 20
console.log("3.", person.gender); // 3. 남자
console.log("4.", person.interests[1]); // 4. music
console.log("5.", person.greeting()); // 5. hello
console.log("5.", person.is tall) //syntax error

(2) 괄호 표기법

console.log("1.", person['name']); // 1. 홍길동
console.log("2.", person['age']); // 2. 20
console.log("3.", person['gender']); // 3. 남자
console.log("4.", person['interests'][1]); // 4. music
console.log("5.", person.greeting()); // 5. hello
console.log("6.", person.["is tall"]); // 5. true

두 방식의 차이?

같은 기능을 하는 것처럼 보이지만 두 기능에는 차이점이 있다.

  • 점 표기법은 여러 단어로 이뤄진 속성의 경우 사용할 수 없다.
  • 괄호 표기법을 사용하면 변수에 저장된 키를 사용해 객체의 속성에 접근할 수 있다.
const key = 'age'; // 객체의 속성에 접근하기 위한 새 변수 할당
console.log(person.key); // undefined
console.log(person[key]); // 20

참고 자료

profile
웹 프론트엔드 UXUI

0개의 댓글