Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 칭기즈칸의 위대한 장군 수부타이
- CSS
- sentry
- 부자의그릇
- Container
- 아웃풋법칙
- try width resources
- 참조 계수
- 쿠버네티스
- 공헌감
- docker
- java
- 과제의 분리
- 뉴 컨피던스
- apache kafka
- node
- HTML
- 비메모리 자원
- 이펙티브 자바
- 모두가 기다리는 사람
- ESG
- 월칙
- colllection
- 수부타이
- kubernetes
- 도파민형 인간
- Infresh
- 히든 스토리
- try-with-resources
- 레퍼런스 복사
Archives
- Today
- Total
Hi
클래스, 생성자, 메서드 본문
클래스, 생성자, 메서드
자바스크립트는 거의 모든 것이 객체이고, 특히 함수 객체로 많은 것을 구현해낸다.
클래스, 생성자, 메서드도 모두 함수로 구현이 가능하다.
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()); // (출력값) zzoon
me.setName("iamhjoo");
console.log(me.getName()); // (출력값) iamhjoo
클래스 및 생성자의 역할을 하는 함수가 있고, 사용자는 new 키워드로 인스턴스를 생성하여 사용할 수 있다.
하지만 이 예제는 자원 낭비를 가져온다. 함수 객체의 프로토타입의 특성을 이용해 해결한다.
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()); // me
console.log(you.getName()); // you
클래스 안의 메서드를 정의할 때는 프로토타입 객체에 정의한 후, new로 생성한 객체에서 접근할 수 있게 하는 것이 좋다.
클래스 메서드를 정의하는 방법
Function.prototype.method = function(name, func) {
if (!this.prototype[name]) {
this.prototype[name] = func;
}
}
ex)
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());
'WEB(웹) > javascript' 카테고리의 다른 글
함수형 프로그래밍의 개념 (0) | 2018.07.09 |
---|---|
상속 (0) | 2018.07.08 |
클래스 기반 언어와 프로토타입 기반 언어 (0) | 2018.07.07 |
클로저 (0) | 2018.07.07 |
join(), split(), includes() (0) | 2018.07.04 |