1. Class와 Objcet
// Object-oriented programming
// class : template (클래스는 뼈대만)
// object : instance of a class
// (실제로 데이터를 통해서 값을 얻는건 Object)
// JavaScript classes
// - introduce in ES6
// - syntactical sugarover prototype-based inheritance
JavaScript
복사
2. Class 예시
// 1. Class declarations
class Person {
//constructor
constructor(name, age){
//field
this.name = name;
this.age = age;
}
//method
speak() {
console.log(`${this.name} : hello!`);
}
}
const ellie = new Person('ellie', 20);
console.log(ellie.name);
console.log(ellie.age);
ellie.speak();
JavaScript
복사
3. Getter and setter
class User {
constructor(firstName, lastName, age){
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
// call stack을 방지하기위해 age에 변수를 바꿔주는게 일반적이다.
// 동일하게 설정하면 계속적으로 호출해서 call stack
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);
JavaScript
복사
4. Fields( public,private)
// 3. Fields (public , private)
// Too soon!
class Experiment {
publicField = 2;
//# 기호를 붙이면 private
#privateField = 0;
}
const experiment = new Experiment();
console.log(experiment.publicField);
console.log(experiment.privatedField);
JavaScript
복사
5. Static properties and Method
// 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();
JavaScript
복사
ㅁ 상속(Inheritance)
•
삼각형,사각형, 원 같은 도형에 대하여 설정을 할 때 예를 들어본다
•
도형이니깐 Shape Class를 생성
•
공통적인 부분 (width, height, color)는 필드로 선언
•
공통적인 메소드 역시 선언
•
사각형 클래스를 만들고 Shape class를 상속해준다
//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 of`);
}
getArea(){
return this.width * this.height;
}
}
class Rectangle extends Shape{}
class Triangle extends Shape{
draw(){
//부모의 메소드를 호출
super.draw();
//triangle에 새로운 메소드내용 정의
console.log('삼각형')
}
getArea(){
return (this.width * this.height) / 2;
}
toString() {
return `Triangle: color: ${this.color}`;
}
}
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());
//6 Class checking : instance of
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
복사