Object-oriendted programing
class: template
object : instance of a class
JavaScript classes
- introduced in ES6
- syntactical sugar over prototype-based inheritance
1. Class declarations
class Person {
// constructor
constructor(name, age) {
//field
this.name = name;
this.age = age;
}
speak() {
console.log(`${this.name}: hello!`);
}
}
const ellie = new Person("ellie", 20);
console.log(ellie.name);
console.log(ellie.age);
ellie.speak();
2. Getter and setters
class User {
constructor(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = age;
this.age = age;
}
get age() {
return this._age;
}
set age(value) {
this._age = value < 0 ? 0 : value;
}
}
const user1 = new User("스티브", "잡스", -1);
console.log(user1.firstName);
3. Fields (public, private)
Too soon!
class Experiment {
publicField = 2;
#privateField = 0;
}
const experiment = new Experiment();
console.log(experiment.publicField);
console.log(experiment.privateField);
4. static properties and methods
Too soon!
공통적으로 클래스에 사용되는 값일 때 유용
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);
Article.printPublisher();
5. Inheritance
a way 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;
}
}
class Rectangle extends Shape {}
class Triangle extends Shape {
draw() {
super.draw();
console.log("^");
}
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());
console.log(rectangle instanceof Rectangle);
console.log(triangle instanceof Rectangle);
console.log(triangle instanceof Triangle);
console.log(triangle instanceof Shape);
console.log(triangle instanceof Object);
console.log(triangle.toString()); // 재정의 가능
'JavaScript' 카테고리의 다른 글
[JavaScript] 8. 배열 제대로 알고 쓰자 (0) | 2021.10.22 |
---|---|
[JavaScript] 7. 오브젝트 넌 뭐니? (0) | 2021.10.22 |
[JavaScript] 5. Arrow Function은 무엇인가? 함수의 선언과 표현 (0) | 2021.09.01 |
[JavaScript] 기본 문법 2 (0) | 2021.07.28 |
[JavaScript] 기본 문법 1 (0) | 2021.07.28 |