티스토리 뷰

```
'use strict';
class Person{
    // constructor
    constructor(name, age) {
        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();
// 2. Getter and Setter
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 < 0 ? 0 : value;
    }
    
}
//const user1 = new User('Steve', 'Job', -1);
//console.log(user1.age);
// 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!
// Obejct(들어오는 데이터)에 상관없이 일정한 거라면 static으로  
// static과 static method를 사용하는 것이 메모리 관리에 더 좋다.
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);
// 
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;
    }
    toString(){
        return this.color+', '+this.width;
    }
}
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: instanceOf
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] json  (0) 2020.11.17
[Javascript] Array  (0) 2020.11.09
[javascript] Object  (0) 2020.11.02
[javascript] 데이터타입  (0) 2020.10.22
[javascript] script 태그 위치  (0) 2020.10.19
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/11   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
글 보관함