3. CLASS
• javascript는 객체 지향 언어가 아니었음
• prototype을 이용해 객체 지향을 지원하도록 함
– 그러나 내부적으로는 여전히 모두 함수
• class 키워드로 선언
– 호이스팅이 되지 않음
4. 기본 사용법
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
getPoint() {
console.log(`x: ${this.x}, y: ${this.y}`);
}
}
let pointInstance = new Point(5, 10);
pointInstance.getPoint();
5. ES5에서는…
var Point = (function () {
function Point(x, y) {
this._x = x;
this._y = y;
}
Point.prototype.getPoint = function () {
console.log('x: ' + this._x + ', y: ' + this._y);
};
return Point;
}());
var pi = new Point(5,10);
pi.getPoint();
6. CONSTRUCTOR
• 객체를 초기화하기 위한 특수 메소드
– 인스턴스 생성
• 생성자(Constructor) 메소드는 한번만 사용가능
// new 객체명() 으로 호출되면 수행되는 메소드
7. PROPERTY
• 클래스의 멤버변수 : 클래스 블록{~}안쪽에 선언 할 수 없음
• 반드시 생성자(Constructor)에서 this.변수명 을 사용해 초기화
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
this.z = 100;
}
}
let pointInstance = new Point(5, 10);
console.log(pointInstance.z);
8. GETTER AND SETTER
• 프로퍼티의 값을 가져오거나 세팅할 때 사용하는 메소드
• get, set 키워드를 사용하여 함수로 정의함
• 단 인스턴스에서 사용시 property 처럼 사용한다
• getter는 반드시 return 값이 있어야 한다
9. GETTER AND SETTER
class Point {
constructor() {
this.x = 0;
this.y = 0;
}
get getPointX(){ return this.x; }
set setPointX(pointX){ this.x = pointX; }
get getPointY(){ return this.x; }
set setPointY(pointY){ this.y = pointY; }
}
let pi = new Point();
pi.setPointX = 5;
pi.setPointY = 10;
console.log(`x:${pi.getPointX}, y:${pi.getPointY}`);
10. STATIC METHOD
• 메소드명 앞에 static을 사용
• 인스턴스를 생성하지 않고도 바로 사용 가능
– ex> Math.random() 같은..
11. class SuHak {
static pow(x, p){
let result = x;
for(let i=0; i<p-1; i++){
result *= x;
}
return result;
}
}
console.log( SuHak.pow(2,10) );
12. INHERITANCE
• 부모의 프로퍼티 메소드를 모두 자식이 갖음
• extends 키워드를 사용
• 기본 생성자가 정의된 클래스만 상속이 가능하다.
– 생성자에서 반드시 super를 이용해 부모의 생성자를 호출해줘야 한다.