this(심화?)
이벤트
const header = document.querySelector('.header');
header.addEventListener('click', function() {
console.log(this);
}
* 결과 document에서 가져온 태그가 결과로 나온다
- addEventListener에 콜백함수는 호출이 아니라 선언만 된거다.
- this는 함수가 호출이 될때 결정 된다고 했다
- 위에 코드만 봤을때는 실질적으론 this가 무엇인지 알수는 없다
- 공식문서에서는 addEventListener에 this는 이벤트가 일어나는 태그를 가리킨다고 되어있다
- 그래서 아마 addEvent에Listener는 내부적으로 다음처럼 되있을 거라고 추측 할 수 있다
const header = {
addEventListener: function(envent, callback) {
callback.call(this);
callback.call(header);
}
}
* 다음처럼 되어있을거라고 추론 할 수 있다
이벤트에서 콜백함수가 화살표 함수이면?
const header = document.querySelector('.header');
header.addEventListener('click', () => {
console.log(this);
}
* 결과 window가 나온다
- 화살표 함수는 부모의 this을 가리킨다
- 화살표 함수의 부모를 addEventListener라고 생각하면 안된다
- addEventListener은 함수 호출이고, addEventListener의 콜백함수는 함수 선언이다. 둘이 엄밀히 다르다!!!
bind, apply, call 차이
- a.bind(header)는 this를 header로 바꾸어 새로운 함수를 만드는것이다.
- call과 apply는 새로운 함수를 만들고 호출까지 한다고 생각하자
- a.call(header) === a.apply(header) === a.bind(header)()로 생각하면 된다.
그러면 call과 apply에 차이는?
- call은 두번째 매개변수를 순서대로 보내고, apply은 배열로 보낸다
- 첫번째 매개변수는 둘다 this이다
function add(a, b) {
return a + b;
}
add.apply(null, [5, 8]); // 8
add.call(null, 5, 8); // 8
Author And Source
이 문제에 관하여(this(심화?)), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
https://velog.io/@spearjin/this심화
저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)
const header = document.querySelector('.header');
header.addEventListener('click', function() {
console.log(this);
}
* 결과 document에서 가져온 태그가 결과로 나온다
const header = {
addEventListener: function(envent, callback) {
callback.call(this);
callback.call(header);
}
}
* 다음처럼 되어있을거라고 추론 할 수 있다
const header = document.querySelector('.header');
header.addEventListener('click', () => {
console.log(this);
}
* 결과 window가 나온다
- a.bind(header)는 this를 header로 바꾸어 새로운 함수를 만드는것이다.
- call과 apply는 새로운 함수를 만들고 호출까지 한다고 생각하자
- a.call(header) === a.apply(header) === a.bind(header)()로 생각하면 된다.
그러면 call과 apply에 차이는?
- call은 두번째 매개변수를 순서대로 보내고, apply은 배열로 보낸다
- 첫번째 매개변수는 둘다 this이다
function add(a, b) {
return a + b;
}
add.apply(null, [5, 8]); // 8
add.call(null, 5, 8); // 8
Author And Source
이 문제에 관하여(this(심화?)), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@spearjin/this심화저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)