본문 바로가기

개발/자바스크립트∥

[자바스크립트] prototype과 리팩토링

반응형

1. 프로토타입 소개

자바스크립트의 함수는 프로토타입으로 구성되어있습니다.

//prototype.js

function Person() {} //Person 객체 생성
Person.prototype.eyes = 2; // Person의 eyes프로퍼티를 생성 후 2를 대입함.
Person.prototype.nose = 1; // Person의 nose프로퍼티를 생성 후 1를 대입함.
const Na  = new Person(); // Na라는 Person의 새 객체를 생성함.
console.log(Na.eyes); // => 2

이를 보기 쉽게 표로 표현하면 다음과 같습니다.

객체,함수,prototype object의 관계

2. class타입으로 리팩토링 하기

기존의 프로토타입의 함수를 es6에 새로 도입된 class함수 타입으로 리팩토링 해보겠습니다.

//prototype.js

function fullstack(backend, frontend) {
    this.backend = backend
    this.frontend = frontend

    fullstack.prototype.getBackend = () => this.backend
    fullstack.prototype.setBackend = () => this.backend = backend

    fullstack.prototype.getFrontend = () => this.frontend
    fullstack.prototype.setFrontend = () => this.frontend = frontend
}

const Fullstack = new fullstack('java','javascript')
console.log(Fullstack) //fullstack { backend: 'java', frontend: 'javascript' }

위에 prototype타입을 class타입으로 바꾸면 다음과 같습니다.

//class.js

class fullStack {
    constructor(backend,frontend) {
        this.backend = backend
        this.frontend = frontend
    }
    getBackend(){
        return this.backend
    }
    getFrontend(){
        return this.frontend
    }
    setBackend(){
        this.backend = backend
    }
    setFrontend(){
        this.frontend = frontend        
    }
}

const Fullstack = new fullstack('java','javascript')
console.log(Fullstack) //fullstack { backend: 'java', frontend: 'javascript' }

한결 코드가 간결해지고 가시적으로 변경된 것을 알수 있습니다.

반응형