-
명시적으로 class라고 선언함으로써 ES5에서 일반함수와 생성자의 구분이 용이해짐
기존 ES5문법대비 생성자와 메서드를 한번에 클래스라는 형태로 보다 구조적으로 패키징가능
일일이 prototype에 메서드를 등록할 필요없이 메서드 등록이 간결해짐
상황에 따라서 메서드에 등록되는 this값을 일일 고정할 필요가 없어짐class FontStyle { constructor(el, opt) { const def = { color: 'gray', size: '100px' } const result = { ...def, ...opt }; if (!el) return console.error('첫번째 인수는 필수입력사항입니다.') this.el = document.querySelector(el); } changeColor(color) { this.el.style.color = color; } changeSize(size) { this.el.style.size = size; } } const item1 = new FontStyle('h1'); item1.changeColor('hotpink');
extends로 클래스 기능 확장
class FontStyle { constructor(el, opt) { const def = { color: 'gray', size: '100px' } const result = { ...def, ...opt }; if (!el) return console.error('첫번째 인수는 필수입력사항입니다.') this.el = document.querySelector(el); } changeColor(color) { this.el.style.color = color; } changeSize(size) { this.el.style.fontSize = size; } } const item1 = new FontStyle('h1'); item1.changeColor('hotpink'); //extends 는 다른 클래스의 메서드 기능을 확장 class BoxStyle extends FontStyle { constructor(el) { //확장된 FontStyle의 생성자 내용을 가져옴 //만약 BoxStyle전용의 추가값을 생성자를 통해서 전달할때는 super()아래쪽에 추가 super(el); } changeWidth(wid) { this.el.style.width = wid; } changeHeight(ht) { this.el.style.height = ht; } changeBg(bg) { this.el.style.backgroundColor = bg; } } const box1 = new BoxStyle('.box1'); box1.changeWidth('200px'); box1.changeHeight('200px'); box1.changeBg('hotpink'); //BoxStyle로 생성된 인스턴스이지만 FontStyle의 메서드를 호출가능 box1.changeColor('white'); box1.changeSize('40px')
'🐶 etc > 2022기록' 카테고리의 다른 글
배열 (0) 2023.03.29 Symbold (0) 2022.11.02 객체지향의 개념 (생성자함수, prototype, ES5) (0) 2022.11.02 console.dir(btn)/addEventListener (0) 2022.10.26 for문▶forEach/maps/for of/for in (0) 2022.10.26 댓글