본문 바로가기

프로그래밍/JavaScript

프토토타입 & 클래스

프로토타입

  • 같은 객체 생성자 함수를 사용할 경우에 특정 함수 또는 값을 재사용할 수 있도록 만들어주는 역할을 한다.
  • 자바에서의 클래스와 비슷한 역할을 한다고 생각해도 되겠다. 상속이나 생성자 등을 활용할 수 있기 때문에 어느 정도유사한 기능을 한다고 생각할 수 있다.
function Person(name, age, score) {
    this.name = name;
    this.age = age;
    this.score = score;
}

Person.prototype.checkScore = function () {
    console.log(this.score);
}

Person.prototype.greetings = '안녕';

const person1 = new Person('철수', 20, 40);
const person2 = new Person('영희', 16, 60);

person1.checkScore();
person2.checkScore();

console.log(person1.greetings);
console.log(person2.greetings);

 

결과값은 40, 60, '안녕', '안녕'이 나타나게 된다.

 

  • 프로토타입은 추가적으로 생성자를 상속받을 수가 있다.
function Person(name, age, score) {
    this.name = name;
    this.age = age;
    this.score = score;
}

function 철수 (name, age) {
    Person.call(this, '철수', age, score);
}

철수.prototype = Person.prototype;

const person1 = new 철수(20, 40);

 

  • call()메소드를 통해 부모 객체를 호출해야 한다. 이 때 첫 매개변수에는 this를 통해 현재의 함수에 적용시킨다는 것을 선언 후 부모 객체에서 선언해야 하는 변수들을 다음 매개변수에 차례로 기입해주어야 한다.
  • 추가로 prototype을 공유하기 위해 상속받은 객체 생성자 함수를 부모 객체의 prototype으로 설정해주는 과정을 거쳤다.

 

클래스

  • ES6부터 지원하게 된 기술이다. 기존의 prototype을 이용한 생성자 선언을 넘어 더 명확하고 깔끔하게 코드를 구현하는 것이 가능해지게 되었다.
  • 기본적으로는 자바나 C#등에서 쓰이는 클래스와 같은 개념이라고 생각하면 된다.
class Person {
    constructor(name, age, score) {
        this.name = name;
        this.age = age;
        this.score = score;
    }
    
    checkScore() {
        console.log(score);
    }
}

const person1 = new Person('철수', 20, 40);
const person2 = new Person('영희', 16, 60);

person1.checkScore();
person2.checkScore();

 

  • 다른 언어와 마찬가지로 extends키워드를 사용해 부모 클래스를 자식 클래스가 더 쉽게 상속받을 수 있게 되었다.
  • 부모 클래스를 상속받을 때 super()메소드는 부모 클래스의 생성자를 가리키게 되어 다시 재정의하는데 시간을 들일 필요가 없게 된다.
class Person {
    constructor(name, age, score) {
        this.name = name;
        this.age = age;
        this.score = score;
    }
}

class 철수 extends Person {
    constructor(age, score) {
        super('철수', age, score);
    }
}

const person1 = new 철수(20, 40);

'프로그래밍 > JavaScript' 카테고리의 다른 글

배열의 내장함수  (0) 2019.12.07
자바스크립트 문제 풀이 (2)  (0) 2019.11.28
자바스크립트 문제 풀이 (1)  (0) 2019.11.26
var과 let, const  (0) 2019.08.22
this  (0) 2019.08.21