ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Javascript] 객체
    Javascript 2024. 4. 5. 08:31

    객체 : class

    • 변수:field 와 함수:method 의 집합
    • Javascript는 Prototype 기반의 객체지향언어이다. 객체를 원형(prototype) 형태로 생성하고, 그 안에 기능을 위한 변수나 함수를 추가하는 방법으로 그룹화 하는 개념
    • 객체는 자주 사용하게 될 기능들을 묶어서 외부의 스크립트 파일로 분리해 내는 용도로 주로 사용한다. 이렇게 만든 스크립트 파일은 여러개의 HTML파일에 의해서 참조하여 재사용할 수 있다.
    const food1 = {
      name: '햄버거',
      price: 5000,
      vegan: false
    };
    
    console.log(food1);
    
    console.log(
      food1.name, // 마침표 프로퍼티 접근 연산자
      food1['price'] // 대괄호 프로퍼티 접근 연산자
    );
    
    //접근연산자를 이용해서 프로퍼티 추가, 수정 가능
    
     삭제
    delete food1.name;
    delete food1['price'];
    delete food1[hobby]; // 없는 프로퍼티를 제거해도 오류가 발생하지는 않음

     

    프로퍼티 접근 방식 

    1. 마침표 프로퍼티 접근 연산자

    2. 대괄호 프로퍼티 접근 연산자
    - 아직 선언되지않은 프로퍼티를 접근할 때, 점표현식을 사용하면 접근할 수없는 오류가 발생하지만 괄호표현식은 가능

    - 특정 기능을 구현하고자할 때, for 루프 대신 효율적으로 사용할 수 있음

     

    식별자 명명 규칙에 어긋나는 키 이름 사용시 : 

    const obj = {
    	1: '하나', // 숫자도 객체의 키로는 사용 가능
    	'ab-cd': 'ABCD', // 문자 포함 시 키도 따옴표로 감싸야 함
    	's p a c e': 'Space'
    }
    // 대괄호 프로퍼티 접근 연산자로만 가능
    console.log(
    	obj[1],
    	obj['ab-cd'],
    	obj['s p a c e']
    );
    
    // ⚠️ 오류 발생
    // console.log(
    //   obj.1,
    //   obj.ab-cd,
    //   obj.s p a c e
    // );
    

     

    객체나 배열을 키값으로 사용시

    const objKey = { x: 1, y: 2 };
    const arrKey = [1, 2, 3];
    
    const obj = {
      [objKey]: '객체를 키값으로',
      [arrKey]: '배열을 키값으로'
    }
    
    console.log(obj);
    // {[object Object]: '객체를 키값으로', 1,2,3: '배열을 키값으로'}
    
    //실제 해당 객체나 배열의 내용이나 참조값이 키가 되는 것이 아님, 객체와 배열이 그 자체가 아니라 문자열로 치환되어 키가 됨

     

    생성자 함수

    function으로 선언된 함수는 기본적으로 생성자 함수의 기능을 갖는다

    • 생성자 함수명은 일반적으로 대문자로 시작 - 파스칼 케이스
    • 생성자 함수로 만들어진 객체를 인스턴스 instance 라 부름
    • this.~로 생성될 인스턴스의 프로퍼티들 정의
    • 생성자 함수는 new 연산자와 함께 사용
    • 암묵적으로 this 반환
    • 생성자 함수에서는 메서드 정의 불가 - 객체 리터럴과 클래스에서는 가능
    function 생성자명(속성1, 속성2, 속성3...) {
    
    this.속성1 = 속성1;
    
    this.속성2 = 속성2;
    
    this.속성3 = 속성3;
    
    }
    
    var 인스턴스1 = new 생성자(속성1, 속성2, 속성3...);
    
    var 인스턴스2 = new 생성자(속성1, 속성2, 속성3...);

     

    인스턴스(instance) : 객체 지향 프로그래밍에서 인스턴스는 해당 클래스의 구조로 컴퓨터 저장공간에서 할당된 실체를 의미한다. 여기서 클래스는 속성과 행위로 구성된 일종의 설계도이다. OOP에서 객체는 클래스와 인스턴스를 포함한 개념

    => 비슷한 성질을 가진 여러개의 객체를 만들기 위해서 생성자 함수(Constructor)를 만들어 찍어내듯이 사용하는데 이렇게 생성된 객체

    // 객체를 만들기 위한 생성자함수를 생성
    function Board(color){
    	this.color = color;
        this.introduce = function(){
        	return `${this.color}색 입니다`;
        }
    }
    
    const col1 = new Board('Yellow');
    // 위 과정을 통해 col1이란 인스턴스가 생성됨
    
    const col2 = new Board('white');
    const col3 = new Board('blue');
    ...
    // 위와 같이 수 많은 인스턴스를 생성할 수 있음
    //기본적으로 생성된 인스턴스는 원래의 객체인 클래스나 프로토타입이 가지고 있는 프로퍼티(property)와 메소드(method)를 모두 상속(inheritence)받는다.
    
    console.log(Board('pink')); //new를 붙이지 않으면 undefined 반환

     

    프로토타입 prototype - 자바스크립트 객체지향의 중심

    - 모든 객체는 prototype 속성 객체를 가지고 있음
    - 생성자의 prototype에 객체를 생성하면 모든 인스턴스가 공동으로 사용 가능
    - getter, setter, toString 등의 메소드를 prototype에 생성하면 메모리 절약 가능

    function YalcoChicken (name, no) {
      this.name = name;
      this.no = no;
      this.introduce = function () {
        return `안녕하세요, ${this.no}호 ${this.name}점입니다!`;
      }
    }
    
    const chain1 = new YalcoChicken('판교', 3);
    console.log(chain1); // YalcoChicken {name: '판교', no: 3, introduce: ƒ}
    
    // 본사에서 새 업무를 추가
    // 프로토타입: 본사에서 배포하는 메뉴얼이라고 이해
    YalcoChicken.prototype.introEng = function () {
      return `Welcome to Yalco Chicken at ${this.name}!`;
    };
    
    console.log(chain1.introEng()); // Welcome to Yalco Chicken at 판교!
    console.log(new YalcoChicken('강남', 17).introEng()); //Welcome to Yalco Chicken at 강남!

     

    다른방식으로 만든 객체와의 차이

    function YalcoChicken (name, no) {
      this.name = name;
      this.no = no;
      this.introduce = function () {
        return `안녕하세요, ${this.no}호 ${this.name}점입니다!`;
      }
    }
    
    function createYalcoChicken (name, no) {
      return {
        name, no,
        introduce () {
          return `안녕하세요, ${this.no}호 ${this.name}점입니다!`;
        }
      }
    }
    // 객체 리터럴
    const chain1 = {
      name: '판교', no: 3,
      introduce: function () {
        return `안녕하세요, ${this.no}호 ${this.name}점입니다!`;
      }
    };
    
    // 객체 반환 함수
    const chain2 = createYalcoChicken('강남', 17);
    
    // 생성자 함수
    const chain3 = new YalcoChicken('제주', 24);
    
    console.log(chain1, chain1 instanceof YalcoChicken);
    console.log(chain2, chain2 instanceof YalcoChicken);
    console.log(chain3, chain3 instanceof YalcoChicken);

     

    instanceof :

    • 객체가 특정 생성자 함수에 의해 만들어졌는지 여부 반환
    •  인스턴스와 생성자의 일치 여부 반환
    •  형태: 인스턴스명 instanceof 생성자명 // 일치할 경우 true 반환
Designed by Tistory.