본문 바로가기

Front-End: Web/JavaScript

[코딩애플] js part 2-5. ES6 방식으로 안쉽게 구현하는 상속기능(Class)

반응형

객체지향 4. ES6 방식으로 안쉽게 구현하는 상속기능(Class)

클래스(Class)

class 부모 {
    constructor(){
        this.name = 'Kim';
    }
}
  • ES6에서 constructor를 만드는 방법이다(신문법).
var 자식 = new 부모();
console.log(자식); // 부모 {name: 'Kim'}

함수를 추가하기

  1. constructor에 추가하던지 (보임)
class 부모 {
    constructor(){
        this.name = 'Kim';
        this.sayHi = function(){ console.log('Hello'); }
    }
}
  1. 밑에 쓰던가 (안보이는데 부모의 유전자(prototype)에 있음)
    • 모든 자식들이 사용할 수 있도록 내장함수가 됨.
    • 관리가 편함(기능 수정, ... 등)
class 부모 {
    constructor(){
        this.name = 'Kim';
    }
    sayHi(){
        console.log('hello');
    }
}

(+) 추가

자식.__proto__ == 부모.prototype

Object.getPrototypeOf()

담은 오브젝트의 부모 유전자를 출력해준다.

Object.getPrototypeOf(자식); // 부모님 prototype을 출력해주세요~

즉,

자식.__proto__ == Object.getPrototypeOf(자식) == 부모.prototype

class 안에 함수 여러개 추가하기

class 부모 {
    constructor(){
        // 보이는 유전자
        this.name = 'Kim';
    }
    // 안보이는 유전자
    sayHi(){
        console.log('hello');
    }
    sayHello(){
        console.log('hello')
    }
}

혹은 이렇게도 가능.

class 부모 {
    constructor(){
        this.name = 'Kim';
    }
    sayHi(){
        console.log('hello');
    }
}
부모.prototype.sayHello = function(){...}

class의 constructor 안에 파라미터 추가하기

class 부모 {
    constructor(파라미터){
        this.name = 파라미터;
    }
    sayHi(){
        console.log('hello');
    }
}

var 자식 = new 부모('dddd');

객체지향 문법을 쓰는 이유

Object를 여러 개 만들어 쓰려고 하는 것

반응형