Object-oriendted programing
class: template
object: instance of a class
JavaScript classes
-- introduced in ES6
-- syntactical sugar over prototype-based inheritance
class Person {
// constructor
constructor(name, age) {
// fields
this.name = name;
this.age = age;
}
// methods
speak() {
console.log(`${this.name}: hello!`);
}
}
const amanda = new Person('amanda', 29);
console.log(amanda.name); // amanda
console.log(amanda.age); // 29
amanda.speak(); // amanda: hello!
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;
this._age = value < 0 ? 0 : value;
}
}
const user1 = new User('Steve', 'Job', -1);
console.log(user1.age);
#privateField 는 Class내부에서만 값이 보여지고 접근이 되고 변경이 가능하지만
Class외부에서는 이 값을 읽을 수도 변경할 수도 없다.
class Experiment {
publicField = 2;
#privateField = 0;
}
const experiment = new Experiment();
console.log(experiment.publicField); // 2
console.log(experiment.privateField); // undefined
Object에 상관없이 공통적으로 class에서 쓸 수 있는 거라면 static 과 static 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);
Article.printPublisher();
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 {
// overiding
draw() {
super.draw(); // 공통적으로 정의한 부모의 메소드 호출하는 법
console.log('🔺');
}
getArea() {
return (this.width * this.height) / 2;
}
}
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 blue color!
// 🔺
console.log(triangle.getArea()); // 200
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
// * 우리가 JS에서 만든 모든 Object Class 들은 자바스크립트의 Object를 상속한 것이다.