1. Class 선언하기 (declarations)
class: template
object: instance of a class
class Person {
// 생성자 (constructor)
constructor(name, age) {
// fields
this.name = name;
this.age = age;
}
// 매서드 (methods)
speak() {
console.log(`${this.name}: hello!`);
}
}
// new 라는 키워드를 사용해서 새 instance를 생성.
const ellie = new Person('ellie', 20);
console.log(ellie.name); // -> [ellie]
console.log(ellie.age); // -> [20]
ellie.speak(); // -> [ellie: hello!]
2. Getter and setters (캡슐레이션)
class User {
constructor(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
get age() {
return this._age;
}
set age(value) {
// if (value < 0) {
// throw Error('age can not be negative');
// }
this._age = value < 0 ? 0 : value;
}
}
const user1 = new User('Steve', 'Job', -1);
console.log(user1.age); // -> [0]
3. Fields (public, private)
class Experiment {
publicField = 2;
#privateField = 0;
}
const experiment = new Experiment();
console.log(experiment.publicField); // -> [2]
console.log(experiment.privateField); // -> [undefined]
4. Static properties and methods
최근에 추가되서 많이 사용되지 않음.
잘 이해가 되지 않음.
class Article {
static publisher = 'Dream Coding';
constructor(articleNumber) {
this.articleNumber = articleNumber;
}
static printPublisher() {
console.log(Article.publisher);
}
}
const article1 = new Article(1);
const article2 = new Article(2);
console.log(Article.publisher); // -> [Dream Coding]
Article.printPublisher(); // -> [Dream Coding]
5. 상속과 다양성 (Inheritance)
a way for one class to extend another class.
class Shape {
constructor(width, height, color) {
this.width = width;
this.height = height;
this.color = color;
}
draw() {
console.log(`drawing ${this.color} color!`);
}
getArea() {
return this.width * this.height;
}
}
// "extends" 이용
class Rectangle extends Shape {}
class Triangle extends Shape {
draw() {
super.draw(); // super(부모의 매서드 호출)
console.log('🔺');
}
getArea() {
return (this.width * this.height) / 2;
} // 이렇게 "재정의" 할 수 있음 (over writing)
toString() {
return `Triangle: color: ${this.color}`;
}
}
const rectangle = new Rectangle(20, 20, 'blue');
rectangle.draw(); // -> [drawing blue color!]
console.log(rectangle.getArea()); // -> [400]
const triangle = new Triangle(20, 20, 'red');
triangle.draw(); // -> [drawing red color!]
// -> [🔺]
console.log(triangle.getArea()); // -> [200]
6. 오브젝트가 클래스를 이용해서 생성됐는지 확인 (Class checking: instanceOf)
console.log(rectangle instanceof Rectangle); // -> [true]
console.log(triangle instanceof Rectangle); // -> [false]
console.log(triangle instanceof Triangle); // -> [true]
console.log(triangle instanceof Shape); // -> [true]
console.log(triangle instanceof Object); // -> [true]
// 자바스크립트의 모든 오브젝트는 Object를 상속 [ex. toString();]
console.log(triangle.toString()); // -> [Triangle: color: red]
let obj = { value: 5 };
function change(value) {
value.value = 7;
}
change(obj);
console.log(obj);
7. JavaScript Reference 참고 사이트