조금 더 연관있는 데이터를 모아주는 역할을 한다.
// Object-oriented programming
// class: template
// object: instance of a class
// JavaScript classes
// - introduced in ES6
// - syntactical sugar over prototype-based ingeritance
class Person{
// constructor
constructor(name, age) {
// fields
this.name = name;
this.age = age;
}
// methods
speak() {
console.log(`${this.name}: hello!`);
}
}
const ellie = new Person('ellie', 20);
console.log(ellie.name);
console.log(ellie.age);
ellie.speak();
class User {
constructor(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
get age() {
return this._age;
}
set age(value) {
this._age = value < 0 ? 0 : value;
}
}
const user1 = new User('Steve', 'Job', -1);
console.log(user1.age);
this.age
는 get age()
this.age = age
는 set age(value)
를 호출한다.this.age = value
는 set age(value)
를 호출하기 때문에set age()
내부에선 age
를 _age
|| pre_age
등으로 바꿔 줄 필요가 있다.set
과 get
에서 동일해야 작동한다.// Too soon!
// https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Classes/Private_class_fields
class Experiment {
publicFiedl = 2;
#privateField = 0;
}
const experiment = new Experiment();
console.log(experiment.publicFiedl);
console.log(experiment.privateField)
//
// Too soon
class Article {
static publisher = 'Dream Coding';
constructor(articlieNimber) {
this.articlieNimber = articlieNimber;
}
static printPublisher() {
console.log(Article.publisher);
}
}
Article.printPublisher();
// 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 of`);
}
getArea() {
return this.width * this.height;
}
}
class Rectangle extends Shape{}
class Triangle extends Shape{
draw() {
super.draw();
console.log('aaa');
}
getArea() {
return (this.width * this.height) / 2;
}
}
const rectangle = new Rectangle(20, 20, 'blue')
rectangle.draw();
console.log(rectangle.getArea());
const triangle = new Triangle(20, 20, 'red');
triangle.draw();
console.log(triangle.getArea());
super
을 통해 부모의 값을 가져올 수 있다.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
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference
JavaScript MDN Reference