만족스러운 개발
ES5 객체지향 문법 > ES6
재봉팔
2022. 2. 19. 11:53
- 객체지향
- 선택자와 이벤트를 통채로 기능 단위로 패키징을 해서 해당 기능이 필요할때마다 복사본 객체 형성
- 객체지향 구조
- 멤버변수 + 메서드
- 멤버변수 : 특정 기능 전용으로 쓰이는 변수 값들
- 메서드 : 특정 기능 전용으로 쓰이는 함수들
- 멤버변수 + 메서드
- 생성자 함수 (constructor)
- 특정 기능을 복사하기 위한 특별한 함수, 인스턴트를 생성하는 함수 ex) 붕어빵 틀
- 인스턴스 (instance)
- 생성자 함수를 통해서 실제로 복사되는 결과물 ex) 붕어빵
- 프로토타입 (prototype)
- 생성자 함수 생성시 자동적으로 만들어지는 공통의 저장 공간
- 같은 생성자 함수를 통해서 만들어진 인스턴스들은 해당 생성자의 프로토타입 공간을 공유
- 생성자 함수 안쪽의 this
- 해당 생성자를 통해서 앞으로 복사가 될 인스턴스 객체를 지칭
- 생성자 안쪽의 this가 다른 값을 지칭하는 상황들
- 이벤트문 안쪽의 this : 이벤트가 발생한 대상을 지칭
- each문 안쪽에서의 this : 현재 반복을 돌고 있는 각 대상을 지칭
- $.ajx문 안에서의 this : 해당 메서드를 통해서 비동기식으로 전달 받은 데이터를 지칭
- setTimeout안에서의 this : window객체를 지칭
- 위의 경우일 때 안쪽 this를 원하는 값으로 고정하는 방법
- 해당 this값을 감싸는 함수에 .bind(고정할 값)
<div id="tab1">
<ul>
<li class="on">button1</li>
<li>button2</li>
<li>button3</li>
</ul>
<section>
<article class="on">BOX1</article>
<article>BOX2</article>
<article>BOX3</article>
</section>
</div>
<div id="tab2">
<ul>
<li class="on">button1</li>
<li>button2</li>
<li>button3</li>
</ul>
<section>
<article class="on">BOX1</article>
<article>BOX2</article>
<article>BOX3</article>
</section>
</div>
var box1 = $(".box1");
var box2 = $(".box2");
box1.on("click", function () {
changeBg(box1);
});
box2.on("click", function () {
changeBg(box2);
});
function changeBg(el) {
el.css({ backgroundColor: "hotpink" });
}
//인수로 문자열을 받아서 제이쿼리 선택자로 변환한 다음에 이벤트 바인딩까지 연결된 구문을 인스턴스로 내보내는 생성자 함수
function Box(el) {
this.selector = $(el);
this.selector.on(
"click",
function () {
this.changeBg(this.selector);
}.bind(this) //이벤트문 안쪽의 this 값을 인스턴스로 고정
);
}
Box.prototype.changeBg = function (el) {
el.css({ backgroundColor: "hotpink" });
};
// 해당 생성자함수로부터 원하는 선택자의 문자열만 집어넣으면 자동으로 해당 요소에 이벤트까지 연결된 기능이 활성화
var box1 = new Box(".box1");
var box2 = new Box(".box2");
ES6 class 문법으로 변환
class Tab {
constructor(sel, opt) {
const defaultOpt = {
btns: "ul li",
boxs: "section article",
activeClass: "active",
};
// const resultOpt = Object.assign({}, defaultOpt, opt);
const resultOpt = { ...defaultOpt, ...opt };
this.frame = $(sel);
this.btns = this.frame.find(resultOpt.btns);
this.boxs = this.frame.find(resultOpt.boxs);
this.activeClass = resultOpt.activeClass;
this.bindingEvent();
}
// Tab 생성자의 프로토타입 공간에 바인딩 이벤트 함수를 등록
bindingEvent() {
this.btns.on("click", (e) => {
const isOn = $(e.currentTarget).hasClass(this.activeClass);
if (isOn) return;
const i = $(e.currentTarget).index();
this.activation(i);
}); // 이벤트문 안쪽의 this 값은 이벤트가 발생한 대상을 지칭하기 때문에 인스턴스로 고정한다
}
activation(index) {
this.btns.removeClass(this.activeClass);
this.btns.eq(index).addClass(this.activeClass);
this.boxs.removeClass(this.activeClass);
this.boxs.eq(index).addClass(this.activeClass);
}
}
<script>
$(document).ready(function () {
new Tab("#tab1", {
activeClass: "on",
});
new Tab("#tab2", {
activeClass: "on",
});
// tab1.bindingEvent();
});
</script>