본문 바로가기
Programming Language/JavaScript

6. 객체

by Ray 2021. 1. 24.

객체

자바스크립트의 객체는 키(key)과 값(value)으로 구성된 프로퍼티(Property)들의 집합.

프로퍼티의 값으로 자바스크립트에서 사용할 수 있는 모든 값을 사용(함수 포함)

객체는 데이터를 의미하는 프로퍼티(property)와 데이터를 참조하고 조작할 수 있는 동작(behavior)을 의미하는 메소드(method)로 구성된 집합.

프로퍼티

프로퍼티는 프로퍼티 키(이름)와 프로퍼티 값으로 구성되며 프로퍼티 키는 식별자이다.

  • 프로퍼티 키 : 빈 문자열을 포함하는 모든 문자열 또는 symbol 값
  • 프로퍼티 값 : 모든 값

메소드

프로퍼티 값이 함수일 경우, 일반 함수와 구분하기 위해 메소드라고 함.

즉, 메소드는 객체에 제한되어 있는 함수를 의미

객체 생성 방법

JavaScript는 프로토타입 기반 객체 지향 언어로서 클래스라는 개념이 없고 별도의 객체 생성 방법이 존재

객체 리터럴

  • 가장 일반적인 자바스크립트의 객체 생성 방식
  • 클래스 기반 객체 지향 언어와 비교할 때 매우 간편하게 객체를 생성
  • 중괄호({})를 사용하여 객체를 생성
  • {} 내에 1개 이상의 프로퍼티를 기술하면 해당 프로퍼티가 추가된 객체를 생성가능
  • {} 내에 아무것도 기술하지 않으면 빈 객체가 생성

ex)

var emptyObject = {}; console.log(typeof emptyObject); // object

var person = { name: 'Lee', gender: 'male', sayHello: function () { console.log('Hi! My name is ' + this.name); } };

console.log(typeof person); // object console.log(person); // {name: "Lee", gender: "male", sayHello: ƒ}

person.sayHello(); // Hi! My name is Lee

Object 생성자 함수

  • new 키워드와 함께 객체를 생성하고 초기화하는 함수
  • 빈 객체 생성 이후 프로퍼티 또는 메소드를 추가하여 객체를 완성하는 방법
  • 생성자 함수를 통해 생성된 객체를 인스턴스(instance)라 함

ex)

// 빈 객체의 생성 var person = new Object(); // 프로퍼티 추가 person.name = 'Lee'; person.gender = 'male'; person.sayHello = function () { console.log('Hi! My name is ' + this.name); };

console.log(typeof person); // object console.log(person); // {name: "Lee", gender: "male", sayHello: ƒ}

person.sayHello(); // Hi! My name is Lee

생성자 함수

  • 마치 객체를 생성하기 위한 템플릿(클래스)처럼 사용하여 프로퍼티가 동일한 객체 여러 개를 간편하게 생성
  • 생성자 함수 이름은 일반적으로 대문자로 시작
  • 프로퍼티 또는 메소드명 앞에 기술한 this는 생성자 함수가 생성할 인스턴스(instance)를 가리킴
  • this에 연결(바인딩)되어 있는 프로퍼티와 메소드는 public(외부에서 참조 가능)
  • 생성자 함수 내에서 선언된 일반 변수는 private(외부에서 참조 불가능)

ex)

function Person(name, gender) { var married = true; // private this.name = name; // public this.gender = gender; // public this.sayHello = function(){ // public console.log('Hi! My name is ' + this.name); }; }

var person = new Person('Lee', 'male');

console.log(typeof person); // object console.log(person); // Person { name: 'Lee', gender: 'male', sayHello: [Function] }

console.log(person.gender); // 'male' console.log(person.married); // undefined

객체 프로퍼티 접근

프로퍼티 키

  • 일반적으로 문자열을 지정
  • 문자열이나 symbol 값 이외의 값을 지정하면 암묵적으로 타입이 문자열로 변환
  • 문자열 타입의 값으로 수렴될 수 있는 표현식도 가능
  • 사용 가능한 유효한 이름이 아닌 경우, 반드시 따옴표를 사용하여야 함

ex)

var person = { 'first-name': 'Ung-mo', 'last-name': 'Lee', gender: 'male', 1: 10, function: 1 // OK. 하지만 예약어는 사용하지 말아야 한다. };

console.log(person);

프로퍼티 값 읽기

  • 객체의 프로퍼티 값에 접근하는 방법은 마침표(.) 표기법과 대괄호([]) 표기법이 존재
  • 프로퍼티 키가 유효한 자바스크립트 이름이고 예약어가 아닌 경우 프로퍼티 값은 마침표 표기법, 대괄호 표기법 모두 사용가능
  • 프로퍼티 이름이 유효한 자바스크립트 이름이 아니거나 예약어인 경우 프로퍼티 값은 대괄호 표기법 사용
  • 대괄호([]) 표기법을 사용하는 경우, 대괄호 내에 들어가는 프로퍼티 이름은 반드시 문자열이어야 함

ex)

console.log(person.first-name); // NaN: undefined-undefined console.log(person[first-name]); // ReferenceError: first is not defined console.log(person['first-name']); // 'Ung-mo'

console.log(person.gender); // 'male' console.log(person[gender]); // ReferenceError: gender is not defined console.log(person['gender']); // 'male'

console.log(person['1']); // 10 console.log(person[1]); // 10 : person[1] -> person['1'] console.log(person.1); // SyntaxError

프로퍼티 값 갱신

객체가 소유하고 있는 프로퍼티에 새로운 값을 할당

ex)

var person = { 'first-name': 'Ung-mo', 'last-name': 'Lee', gender: 'male', };

person['first-name'] = 'Kim'; console.log(person['first-name'] ); // 'Kim'

프로퍼티 동적 생성

객체가 소유하고 있지 않은 프로퍼티 키에 값을 할당하면 주어진 키와 값으로 프로퍼티를 생성하여 객체에 추가

ex)

var person = { 'first-name': 'Ung-mo', 'last-name': 'Lee', gender: 'male', };

person.age = 20; console.log(person.age); // 20

프로퍼티 삭제

delete 연산자를 사용하면 객체의 프로퍼티를 삭제

피연산자는 프로퍼티 키

ex)

var person = { 'first-name': 'Ung-mo', 'last-name': 'Lee', gender: 'male', };

delete person.gender; console.log(person.gender); // undefined

delete person; console.log(person); // Object {first-name: 'Ung-mo', last-name: 'Lee'}

for-in 문

for-in 문을 사용하면 객체(배열 포함)에 포함된 모든 프로퍼티에 대해 루프를 수행 가능

ex)

var person = { 'first-name': 'Ung-mo', 'last-name': 'Lee', gender: 'male' };

// prop에 객체의 프로퍼티 이름이 반환된다. 단, 순서는 보장되지 않는다. for (var prop in person) { console.log(prop + ': ' + person[prop]); }

/* first-name: Ung-mo last-name: Lee gender: male */

var array = ['one', 'two'];

// index에 배열의 경우 인덱스가 반환된다 for (var index in array) { console.log(index + ': ' + array[index]); }

/* 0: one 1: two */

'Programming Language > JavaScript' 카테고리의 다른 글

8. 프로토 타입(Proto type)  (0) 2021.01.24
7. 스코프  (0) 2021.01.24
5. 함수  (0) 2021.01.24
4. 제어문  (0) 2021.01.24
3. 연산자  (0) 2021.01.24