자바스크립트를 배워보자! 1.데이터타입 - 2)객체타입

1) 객체란 무엇인가?

  • 자바스크립트의 객체 타입은 원시타입을 제외하고 모두 객체 타입이다.
  • 객체는 프로퍼티로 구성된 집합이며, 키와 값으로 구성된다.
  • 객체의 값에 함수가 할당되면 메서드라 부른다.
  const person = {
      name: ' 김철수', 
      address: '서울 여의도',
      getPoint: function() {
        return 100
      }
  }
  console.log(person.name)  // 프로퍼티 접근
  console.log(person.getPoint()) // 메서드 접근
  • 원시 타입은 값을 변수에 할당하면 확보된 메모리 공간에 실제 값이 저장되는 반면, 객체타입을 변수에 할당하면 참조 값이 저장된다.
  const aPerson = {
      name: ' 김철수', 
      address: '서울 여의도',
      getPoint: function() {
        return 100
      }
  }
  const bPerson = aPerson
  aPerson.name = '김자스'   
  console.log(bPerson.name) // aPerson.name을 재할당했으나. bPerson에도 주소를 참조하므로 동일한 데이터가 나온다.

2) 객체 생성 방법

  • 객체 리터럴
// 중괄호를 이용하여 프로퍼티와 메서드를 할당한다.
const person = {
      name: ' 김철수', 
      address: '서울 여의도',
      getPoint: function() {
        return 100
      }
  }
  • 생성자 함수
    function Person(){
    this.name = '김철수'
    this.address = '서울 여의도'
    this.getPoint = function () {
       return 100
    }
    }
    const person = new Person()
    console.log(person.name)  // 프로퍼티 접근
    console.log(person.getPoint()) // 메서드 접근
    
  • Object 생성자 함수
    const person = new Object()
    person.name = '김철수'
    person.address = '서울 여의도'
    person.getPoint = function () {
     return 100
    }
     console.log(person.name)  // 프로퍼티 접근
     console.log(person.getPoint()) // 메서드 접근
    
  • 클래스
    class Person {
    constructor() {
      this.name = '김철수'
      this.address = '서울 여의도'
    }
      
    getPoint() {
      return 100
    }
    }
    const person = new Person() 
    console.log(person.name)  // 프로퍼티 접근
    console.log(person.getPoint()) // 메서드 접근