본문 바로가기
웹(web)/프론트엔드-javascript

클래스

by 바코94 2020. 6. 27.

클래스는 IE에서 지원하지 않는다. 간단하게 살펴보고 넘어가자.

객체 생성자와 프로토타입에 함수를 등록할 때 편하다.

 

Animal 클래스를 만들고 객체를 만들려면?

class Animal {

  constructor(type, name, sound) {

    this.type = type;

    this.name = name;

    this.sound = sound;

  }

  say() {

    console.log(this.sound);

  }

};

const dog = new Animal("개", "멍멍이", "멍멍");

dog.say();

say가 prototype에 자동으로 등록됨.

 

 

Dog 클래스를 만들려면?

class Dog extends Animal {

  constructor(name, sound) {

    super("개", name, sound);

  }

}

const dog = new Dog("멍멍이", "멍멍");

dog.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("도미노");

pizza.print();

'웹(web) > 프론트엔드-javascript' 카테고리의 다른 글

비구조화 할당(구조분해 할당)  (0) 2020.06.28
falsy 한 값  (0) 2020.06.28
생성자 함수와 상속  (0) 2020.06.27
객체, 배열의 내장함수 정리  (0) 2020.06.27
javascript 추가 기능  (0) 2020.06.27