const arr = [1,2,3,4,5]
let result = [];
for(let i = 0; i<arr.length; i++){
result.push(arr[i]*2);
}
return result
const result = arr.map((el) => el*2);
선언형으로 프로그래밍하면, 유지보수하거나 기능을 추가할때 편하다.(짧잖아~)
class ToggleButton {
constructor(target, text) {
this.$target = target;
this.text = text;
this.button = document.createElement("button");
this.createElement();
this.render();
this.addEvent();
}
addEvent() {
this.button.addEventListener("click", (e) => {
if (this.button.style.textDecoration === "line-through") {
this.button.style.textDecoration = "";
} else this.button.style.textDecoration = "line-through";
});
}
createElement() {
this.$target.appendChild(this.button);
}
render() {
this.button.textContent = this.text;
}
}
const $root = document.getElementById("root");
new ToggleButton($root, "button1");
new ToggleButton($root, "button2");
new ToggleButton($root, "button3");
이렇게 하면 여러개의 버튼을 제작해야하는 명령형보다 더 간단히 할수있다.
=> oop가 이래서 나왔구나.
하지만 여기에도 수정할 부분이 있다. 스타일 자체를 바꾸지 말고, 상태에 의존하도록 만들면 조작이 더 간단해진다.
class ToggleButton {
constructor(target, text, onClick) {
this.$target = target;
this.text = text;
this.button = document.createElement("button");
this.count = 0;
this.onClick = onClick;
this.state = {
clickCount: 0,
toggled: false,
};
this.createElement();
this.render();
this.addEvent();
}
addEvent() {
this.button.addEventListener("click", () => {
this.setState({
clickCount: this.state.clickCount + 1,
toggled: !this.state.toggled,
});
if (this.onClick) this.onClick(this.state.clickCount);
console.log(this.state);
});
}
createElement() {
this.$target.appendChild(this.button);
}
setState(newState) {
this.state = { ...this.state, ...newState };
this.render();
}
render() {
this.button.textContent = this.text;
this.button.style.textDecoration = this.state.toggled
? "line-through"
: "none";
}
}
const $root = document.getElementById("root");
new ToggleButton($root, "button1", (clickCount) => {
if (clickCount % 2 === 0) alert("짝수");
});
new ToggleButton($root, "button2", (clickCount) => {
if (clickCount % 3 === 0) alert("3의배수");
});
new ToggleButton($root, "button3");
강의는 생성자함수를 사용했기에 다소 다른부분이 존재한다.
위에 진행했던 예제들이 상태를 기반으로 한 추상화다.
모두 상태에 의존해서 진행하니 개발자는 상태관리만 잘하면 된다는 장점이 있다.
상태만 추적하면 변경사항을 알기도 쉽다.
물론 단점도 존재한다.
시스템의 규모가 커질수록 상태관리의 난이도가 올라간다.
=> OOP의 단점과 비슷하다. 하지만 장점이 크기에 오늘날 수많은 프레임워크(리액트, 뷰)에서 사용하는 거겠지.
오늘은 여까지!