작성자 : 장기효
검수자 : 배광식
Class
클래스 선언
ES5에서 생성자로 객체를 생성하는 부분에 새로운 문법을 적용한 것
[ES5] 생성자로 함수 선언
function Product(name, price) {
this.name = name;
this.price = price;
this.sell = function () {
console.log('Not on sale');
};
}
Product.prototype.purchase = function () {
console.log('Purchased');
};
var p = new Product('coke', 1000);
p.sell();
[ES6] class로 함수 선언
class Product {
constructor(name, price) {
this.name = name;
this.price = price;
}
sell() {
console.log('Not on sale');
}
purchase() {
console.log('Purchased');
}
}
const p = new Product('coke', 1000);
p.sell();
클래스 상속
Java와 비슷하게 기존 객체를 쉽게 확장해서 사용할 수 있는 문법이 추가되었다.
extends 예약어
class Product {
constructor(name, price) {
this.name = name;
this.price = price;
}
purchase(name, price, amount) {
return 'you bought ' + amount + ' ' + name + 's which cost ' + price;
}
}
class iPhone extends Product {
purchase() {
return 'I got the iphone';
}
}
const i = new iPhone();
i.purchase(); // "I got the iphone"
super 예약어
class Product {
constructor(name, price) {
this.name = name;
this.price = price;
}
purchase(name, price, amount) {
return 'you bought ' + amount + ' ' + name + 's which cost ' + price;
}
}
class iPhone extends Product {
purchase() {
return super.purchase();
}
}
const i = new iPhone();
i.purchase(); // "you bought undefined undefineds which cost undefined"
클래스 기타
그 외 부수적인 클래스 기능으로는 객체를 생성하지 않고도 특정 메서드를 사용할 수 있는 static 예약어가 있다.
static 예약어
class Product {
constructor(name, price) {
this.name = name;
this.price = price;
}
static purchase(name, price, amount) {
return 'you bought ' + amount + ' ' + name + 's which cost ' + price;
}
}
console.log(Product.purchase('iphone', '$1,000', 3)); // you bought 3 iphones which cost $1,000