본문 바로가기

Frontend/자바스크립트 Java Script

[ES6] ES6 클래스 Class 가 존재하기 전 prototype 특수변수 사용

기존 자바스크립트 문법은 클래스가 없고 prototype이라는 특수변수를 통해 상속 기능을 사용했음.

함수를 사용해 클래스를 선언해 사용했음. 즉, 함수가 클래스의 생성자 같은 역할을 함.

function Shape (x, y) {

    this.name = 'Shape';

    this.move(x, y);

}

프로토타입이라고 하는 특수변수를 사용해 각각의 메소드 이름에 함수를 정의하는 방식으로 사용했음.

Shape.prototype.move = function(x, y) {

    this.x = x;

    this.y = y;

};

 

Shape.prototype.area = fuction() {

    return 0;

};

 

// new라는 생성자를 통해 선언

const s = new Shape(0, 0);

console.log(s.area());        ->0

 

// static함수에 생성자 함수 선언

Shape.create = function (x, y) {

    return new Shape(x, y);

};

const s1 = Shape.create(10, 10);  // s1은  shape클래스의 인스턴스가 되어 동일한 결과값이 출력됨

console.log(s1.area());      ->0

 

상속은 prototype을 덮어씌우는 방식으로 부모의 상속되는 객체값을 집어넣었음

function Circle(x, y, radius) {

    Shape.call(this, x, y);   // 부모 함수를 호출

    this.radius = radius;     // 새로 전달된 변수값 추가로 저장

}

 

기존에 선언된 메소드들을 상속받기 위해 프로토타입이라고 하는 변수에 있는 값들을 합병하는 방식으로 메소드들을 상속받음.

자식.prototype = 부모.prototype + 자식메소드

Circle.prototype = {

    ...Shape.prototype,

    area: function() {

        return this.radius * this.radius * Math.PI;

    }

};

const c = new Circle(0, 0, 5);

console.log(c.area());   ->78.53981633974483 원의 면적이 출력됨

 

 

 

이를  ES6에서는 class를 사용해 간결하게 사용 가능.

 

class Shape {

    constructor(x, y) {

        this.name = 'Shape';

        this.move(x, y);

    }

    move(x, y) {

        this.x = x;

        this.y = y;

    }

    area() {

       return 0;

    }

}

 

class Circle extends Shape {     // extends 부모클래스 로 상속

    constructor (x, y, radius) {          // 컨스트럭터에 radius 추가

       super(x, y);                       // 부모의 constructor함수 호출하는 역할. 위의 Shape.call(this, ...)과 동일. 인자값 동일하게 x, y

       this.radius = radius;

    }

    area() {    // 추가적으로 덮어씌우고 싶은 새 정의 함수만 정의하면 됨

       return this.radius * this.radius * Math.PI;

    }

}

 

스태틱 static 표현법

class Circle extends Shape {

    static create(x, y) {                 // static이라는 변수 사용 <- 기존 Shape.create = fuction(...){...}과 동일

        return new Shape(x, y);

    } 

    constructor(x, y) {

        this.name = 'Shape';

        this.move(x, y);

    }

    move(x, y) {

        this.x = x;

        this.y = y;

    }

    area() {

       return 0;

    }

}

 

const s1 = Shape.create(0, 0);  // static메소드 선언

console.log(s1.area());     -> 0

 

 

 

ES7문법

class Shape {

    constructor(x, y) {

        name = 'Shape';    //  인스턴스 변수값 선언대신 변수를 선언해 정의할 수 있음. var, let, const키워드 없이 선언.

                                          <- this.name = 'Shape';

        this.move(x, y);

    }

    move(x, y) {

        this.x = x;

        this.y = y;

    }

    area() {

       return 0;

    }

}