본문 바로가기

자바스크립트

객체지향 프로그래밍(1)

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

더글라스 크락포드는 다음과 같은 함수를 제시하면서 메소드를 정의하는 방법을 소개한다.

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

이 함수를 이용한다면...

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

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

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

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

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