1. Object-oriented programming (객체지향 언어)
- class : template, declare once, no data in
- object : instance of a class, created many times, data in
- JavaScript classes (introduced in ES6) : syntactical sugar over prototype-based inheritance
2. Class declarations
class Person {
// constructor
constructor(name, age) {
// fields
this.name = name;
this.age = age;
}
speak() {
console.log(`${this.name} : hello!`);
}
}
const a = new Person('apple', 20);
console.log(a.name);
console.log(a.age);
a.speak();
3. Getter & Setter
class User {
constructor(firstName, lastName, age) {
this.firstName = firseName;
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', 'Jobs', -1);
console.log(user1.age);
4. Fields (public, private)
- encapsulation(캡슐화)
class Experiment {
publicField = 1;
#privateField = 2;
}
const experiment = new Experiment();
console.log(experiment.publicField); // 1
console.log(experiment.privateField); // undefined
5. Static properties & methods
class Article {
static publisher = 'Dream Coding';
constructor(articleNumber) {
this.articleNumber = articleNumber;
}
static printPublisher() {
console.log(Article.publisher);
}
}
const art1 = new Article(1);
console.log(art1.publisher); // undefined
console.log(Article.publisher); // Dream Coding
Article.printPublisher();
6. Inheritance & Overriding
- a way for one class to extend another class.
clss Shape {
constructor(width, height, color) {
this.width = width;
this.height = height;
this.color = color;
}
draw() {
consolo.log(`drawing ${this.color} color of`);
}
getArea() {
return width * this.height;
}
}
class Rectangle extends Shape {}
class Triangle extends Shape {
draw() {
super.draw();
console.log('^');
}
getArea() { // Overriding
return (this.width * this.height) / 2;
}
}
const rectangle = new Rectangle(20, 20, 'blue');
rectangle.draw();
const triangle = new Triangle(20, 20, 'red');
triangle.draw();
7. Class checking : instanceof
console.log(rectangle instanceof Rectangle); // true
console.log(triangle instanceof Triangle); // true
console.log(triangle instanceof Rectangle); // false
console.log(triangle instanceof Shape); // true
console.log(triangle instanceof Object); // true
'IT > WILT' 카테고리의 다른 글
[JavaScript] 8. Array (0) | 2022.02.25 |
---|---|
[JavaScript] 7. Object (0) | 2022.02.24 |
[JavaScript] 5. 함수의 선언과 표현, Arrow Function (0) | 2022.02.22 |
[JavaScript] 4. 코딩의 기본 operator (0) | 2022.02.20 |
[JavaScript] 3. Data Type, let VS var, hoisting (0) | 2022.02.19 |