자바스크립트에서 클래스 안의 메소드를 정의할 때는 프로토타입 객체에 정의한 후, 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());'자바스크립트' 카테고리의 다른 글
| 객체지향 프로그래밍(3) : 클래스기반 상속 (0) | 2022.04.17 |
|---|---|
| 객체지향 프로그래밍(2) : 프로토타입 상속 (0) | 2022.04.17 |
| ORM 활용 (0) | 2022.04.10 |
| 데이터 인라인 포함하기 (0) | 2022.04.10 |
| 레퍼런스 문제 해결 (0) | 2022.04.10 |