6.1 클래스, 생성자, 메소드

vencott·2021년 6월 2일

C++이나 Java의 경우 class라는 키워드를 사용하여 클래스를 만들지만 자바스크립트에는 class 키워드가 없다

자바스크립트는 거의 모든 것이 객체이고, 특히 함수 객체로 많은 것을 구현해낸다

클래스, 생성자, 메소드 모두 함수로 구현이 가능하다

function Person(arg) {
    this.name = arg;
    this.getName = function () {
        return this.name;
    };
    this.setName = function (value) {
        this.name = value;
    };
}

var me = new Person('zzoon');
console.log(me.getName());

me.setName('iamhjoo');
console.log(me.getName());

이 형태는 기존의 객체지향 프로그래밍 언어에서 객체를 생성하는 코드와 매우 유사하다

함수 Person이 클래스이자 생성자의 역할을 한다

하지만 이 예제에는 문제가 많다

Person()으로 객체를 생성할 때마다 공통적으로 사용할 수 있는 getName()과 setName()을 계속 생성해낸다

이 문제를 해결하려면 자바스크립트의 특성 중 함수 객체의 프로토타입을 이용한다

function Person(arg) {
    this.name = arg;
}

Person.prototype.getName = function() {
  return this.name;
}

Person.prototype.setName = function(value) {
  this.name = value;
}

var me = new Person('me');
var you = new Person('you');

console.log(me.getName());
console.log(you.getName());

위 예제에선 Person함수 객체의 prototype 프로퍼티에 getName()과 setName()을 정의하였다

이렇게 하면 Person함수로 생성되는 객체들은 setName()과 getName()함수를 프로토타입 체이닝으로 접근할 수 있다

이는 곧 불필요한 중복을 줄인다

이와 같이 자바스크립트에서 클래스 안의 메서드를 정의할 때는 프로터타입 객체에 정의한 후, new로 생성한 객체에서 프로토타입 체이닝으로 접근할 수 있게 하는 것이 좋다

다음은 더글라스 크락포드가 소개한 메소드를 정의하는 방법이다

Function.prototype.method = function (name, func) {
    if (!this.prototype[name]) // this의 프로토타입에 name이라는 이름을 가진 프로퍼티(메소드)가 없으면
        this.prototype[name] = func
};

이 패턴을 이용하면 위에서 살펴본 예제는 다음과 같이 작성할 수 있다

Function.prototype.method = function (name, func) {
    if (!this.prototype[name])
        this.prototype[name] = func;
};

function Person(arg) {
    this.name = arg;
}

Person.method('getName', function () {
    return this.name;
});

Person.method('setName', function (value) {
    this.name = value;
});

var me = new Person('me');
var you = new Person('you');

console.log(me.getName());
console.log(you.getName());

출처: 송형주, 고현준 저, 『인사이드 자바스크립트』, 한빛미디어(2014)

profile
Backend Developer

0개의 댓글