Class
Class 실활용 및 staic메소드와 prototype메소드 비교
<div class="font1">Color</div>
<div class="font1">Blue?</div>
<div class="font2">Heropy</div>
<button class="btn1">OK!</button>
<button class="btn2">OK?!</button>
<button class="btn3">Getter?!</button>
class Fonty {
constructor(selector, customOptions) {
const defaulOptions = {
fontSize: '16px',
fontWeight: '700',
color: 'black',
}
this.options = {
...defaulOptions,
...customOptions
}
this.els = document.querySelectorAll(selector)
this.setStyle(this.options)
}
setStyle(style) {
this.els.forEach(el => {
Object.assign(el.style, style)
})
}
static setRed(instance) {
instance.setStyle({
color: 'red'
})
}
static getFamilies() {
return ['serif', 'sans-serif', 'monospace', 'cursive']
}
get fontSize() {
console.log('in Getter', this.options.fontSize)
return this.options.fontSize
}
set fontSize(value) {
console.log('in Setter', value)
}
}
new Fonty('.font1', {
fontSize: '30px',
fontWeight: '400',
color: 'red'
})
const fonty = new Fonty('.font2', {
fontSize: '40px',
fontWeight: '700',
color: 'blue'
})
document.querySelector('.btn1').addEventListener('click', () => {
fonty.setStyle({
color: 'black'
})
})
document.querySelector('.btn2').addEventListener('click', () => {
Fonty.setRed(fonty)
})
console.log(Fonty.getFamilies)
document.querySelector('.btn3').addEventListener('click', () => {
console.log(fonty.fontSize)
fonty.fontSize = '99px'
})
getter, setter
class User {
constructor(first, last) {
this.first = first
this.last = last
}
get fullName() {
return `${this.first} ${this.last}`
}
set fullName(value) {
const res = value.split(' ')
this.first = res[0]
this.last = res[1]
const [first, last] = value.split(' ')
this.first = first
this.last = last
}
}
const heropy = new User('Heropy', 'Park')
console.log(heropy.fullName)
heropy.fullName = 'Leon Miller'
console.log(heropy.fullName)