'javascript class'에 해당되는 글 2건

반응형
// 문법을 엄격하게 봐줌
'use strict';


class Person {

    //생성자
    constructor(name, age){
        this.name = name;
        this.age = age;
    }

    //함수
    speak(){
        console.log(`${this.name}: hello`);

    }
}

const mario = new Person('Mario', 35);
console.log(mario.name);
console.log(mario.age);
mario.speak();


//2. Getter and setters
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('Steave', 'job', -1);
console.log(user1.age);


//4. Static properties and 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();

//5. Inheritance
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();
        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()); 
console.log(triangle.toString());
반응형
블로그 이미지

꽃꽂이하는개발자

,
반응형
class Animal {
  constructor(type, name, sound) {
    this.type = type;
    this.name = name;
    this.sound = sound;
  }
  say() {
    console.log(this.sound);
  }
}
//상속
class Dog extends Animal {
  constructor(name, sound) {
    super("개", name, sound);
  }
}
class Cat extends Animal {
  constructor(name, sound) {
    super("고양이", name, sound);
  }
}
const dog = new Dog("멍멍이", "멍멍");
const cat = new Cat("야옹이", "야옹");
const cats = new Cat("고양이들", "야오오오오오옹");

dog.say();
cat.say();
cats.say();
class Food {
  constructor(name) {
    this.name = name;
    this.brands = [];
  }
  addBrand(brand) {
    this.brands.push(brand);
  }
  print() {
    console.log(`${this.name}을/를 파는 음식점들:`);
    console.log(this.brands.join(", "));
  }
}

const pizza = new Food("피자");
pizza.addBrand("피자헛");
pizza.addBrand("도미노피자");

const chicken = new Food("치킨");
chicken.addBrand("굽네치킨");
chicken.addBrand("동네앞치킨");

pizza.print();
chicken.print();
반응형
블로그 이미지

꽃꽂이하는개발자

,