내 머리속 JS - class

JAEN·2020년 3월 16일
0

내머리속 JS 🙈

목록 보기
14/14

" JavaScript is prototype based Object oriented language. "

Object Oriented Programming

"데이터를 추상화시켜상호작용(interaction)하는 객체들의 집합"

 


CLASS

bluePrint

1. 자바스크립트는 프로토타입 기반 언어

1.1. 클래스 기반 언어

클래스로 객체 자료구조, 기능 정의하고 생성자를 통해 인스턴스 생성

클래스 : 같은 종류 집단에 속하는 속성(attribute), 행위(behavior) 정의한 것
인스턴스 : 오직 클래스 정의된 범위 내에서 작동 (정확성, 안정성, 예측성)

ex) java, python, c#, php

1.2. 프로토타입 기반 언어

클래스 개념이 없음
이미 생성된 인스턴스의 자료구조, 기능 동적으로 변경 가능
생성자 함수는 js에서 클래스이자 생성자 역할

프로토타입 객체: 모든 객체는 부모 역할 담당하는 객체와 연결

 


2. 클래스 정의

2.1 클래스 선언문

var 변수처럼 호이스팅 발생하지 않습니다.
하지만, let 변수와 같이 블록 내에서 호이스팅 발생합니다.

console.log(Dog);		//error!
class Dog{ }

2.2 클래스 표현식

클래스 명은 함수 표현식과 동일하게 클래스 몸체 내부 유효 식별자

const Doggy = class Dog { }
const snoopy = new Doggy()		// Dog { }
new Dog()				//error!

3. 인스턴스

new 연산자와 함꼐 클래스 호출 시 인스턴스 생성

* new 연산자와 함께 호출한 것은 클래스명이 아니무니다! >>> Constructor 이무니다!

Object.getPrototypeof(snoopy).constructor === Dog

* new 연산자 없이 constructor 호출할 수 없으무니다!

4. Constructor

  • 인스턴스 생성하고 클래스 필드 초기화하는 특수 메서드
  • 생략 가능
  • 동적으로 프로퍼티 추가 가능(인스터스 생성 후)
  • 반드시 constructor 안에서 클래스 필드 선언, 초기화

5. 접근자 프로퍼티 (Accessor property)

5.1 getter

  • get 키워드
  • 클래스 필드 접근
  • 메서드 호출 방식이 아닌 프로퍼티 참조형식 (like 클래스 필드 이름)
class Dog{
  constructor() { ... }
  //getter
  get getHand(){
    return this.hand;
  }
}
  
const snoopy = new Dog();
snoopy.getHand;			//snoopy.getHand() ❌

5.2 setter

  • set 키워드
  • 클래스 필드 값 할당
  • 메서드 호출 방식이 아닌 프로퍼티 참조형식 (like 클래스 필드 이름)
class Dog{
  constructor() { ... }
  //setter
  set setBark(pNum){
    return `${pNum}번 멍멍멍`;
  }
}
  
const snoopy = new Dog();
snoopy.setBark = 3;			//snoopy.setHand(3) ❌

6. 정적메서드 Static

클래스 인스턴스 생성 없이도 호출 가능한 메서드 (인스턴스 호출 ❌)
정적 메서드는 this 사용 ❌ (this는 클래스 인스턴스 의미, 인스턴스 생성 전제하에 this 사용하므로..)
= this를 사용한 필요없는 메서드 (전역 객체 주로 사용)

class Dog{
  static runAway(){
    return "FreeDom!!!";
  }
}
  
Dog.runAway()

const snoopy = new Dog();
snoopy.runAway();			//error!!!

7. extends 상속 :: 코드재사용 ↑

부모클래스는 상속 받는 자식 클래스 정의

  • 오버라이딩 : 상위 클래스에 정의된 메서드를 하위 클래스에서 재정의
  • 오버로딩 : 같은 이름 메서드, 다른 타입 or 갯수 파라미터 <<< js에서 지원 ❌
class Dog{
  constructor(pName){
    this.name = pName;
    this.hand = 'front right hand';
  }
  getHand(){
    return this.hand;
  }
  setBark(){
    return `멍멍멍`;
  }
}

class Puppy extends Dog{
  construtor(pName,pNum){
    super(pName)
    this.num = pNum;
  }
  setBark(){
    return `${this.num}번 멍멍멍, ${super.getHand()}도 주세요..!`;
  }
}

8. super 키워드

부모 클래스 참조 or 부모 클래스 호출

  • 부모 클래스의 클래스필드, 메서드 참조
  • constructor 내부 부모 클래스의 constructor 호출; 인스턴스 생성
  • 자식클래스의 [[prototpye]] === 부모클래스
class Dog{
  constructor(){ ... }
  ...
}

class Puppy extends Dog{
  construtor(props){
    super(props);
    ...
  }
  ...
}
  
Puppy.[[prototype]] === Dog
Puppy.prototype.[[prototype]] === Dog.prototype
  
profile
Do myself first! 🧐

0개의 댓글