Skip to content

Latest commit

 

History

History
100 lines (66 loc) · 2.88 KB

File metadata and controls

100 lines (66 loc) · 2.88 KB

back    |    write by Santos

2-3. this


* 이 글은 코어자바스크립트 책을 참고하여 기록하였습니다.

콜백 함수에서 this는 기본적으로 전역객체를 참조하지만, 별도로 this가 될 대상을 지정한 경우에는 그 대상을 참조.

1. this

예시 (Array.prototype.map - this 지정) 😎

Array.prototype.map = function (callback, thisArg){
  var mappedArr = [];
  for (var i = 0; i < this.length; i++){
    var mappedValue = callback.call(thisArg || window, this[i], i, this);
    mappedArr[i] = mappedValue;
  }
  return mappedArr;
}

* 예시를 통해 알아야 할 것들 🤔

  1. this에는 thisArg 값이 있을 경우에는 그 값을, 없을 경우에는 전역객체를 지정.

  2. 첫 번째 인자에는 메서드의 this(배열)의 i번째 요소.

  3. 두 번째 인자에는 i, 즉 index.

  4. 세 번쨰 요소에는 this(배열)자체.

  5. 지정한 결과가 mappedValue에 담겨 mappedArr의 i번째 값으로 할당.

- this에 다른 값이 담기는 이유(전역객체가 아닌 지정된 대상 값)는 제어권을 넘겨 받을 때 call/apply 메서드 첫 번째 인자에 this가 될 대상을 명시적으로 바인딩하기 때문.

예시 (콜백 함수 내부에서의 this) 😎

#1 setTimeout 함수
setTimeout(function (){
  console.log(this);         // Window {...}
}, 300);

#2 Array.prototype.forEach 함수
[1, 2, 3, 4, 5].forEach(function (x){
  console.log(this)          // Window {...} 
});

#3 Event 함수
document.body.innerHTML += '<button id="a">클릭</button>';
document.body.querySelector('#a').addEventListener('click', function (e){
  console.log(this, e);      // <button id="a">클릭</button>
                             // MouseEvent { isTrusted: true, ... }
})

* 예시를 통해 알아야 할 것들 🤔

  1. #1 setTimeout 함수 내부에서 콜백 함수를 호출할 때 call 메서드의 첫 번쨰 인자에 전역객체를 넘김. this는 Window

  2. #2 forEach 함수도 마찬가지로 별도의 this를 지정하지 않았기 때문에, this는 Window

  3. #3 addEventListener 함수 내부에서 콜백 함수를 호출 할때, addEventListener 메서드의 this를 그대로 넘기도록 정의되어 있음. this는 addEventListener를 호출한 HTML 엘리멘트.


읽어 주셔서 감사합니다.


<참고자료>

[책] #코어자바스트립트 - 정재남 지음 -

<콜백함수> this end