자바스크립트에서의 this
자바스크립트에서의 this 란?
자바스크립트에서 this란 간단하게 코드안에서 호출 부분을 보면됩니다.
선언부분이 아닌 호출부분에 따라 this는 달라집니다.
즉,  함수를 호출할 때 this를 바꿔주는 동작을 했나 안했나만 따지면 됩니다.
- this는 기본적으로 window입니다.
function a() {
    console.log(this);
}
a(); // Window {}
그렇다면 우리는 this가 window가 아닌 즉, 바뀌는 경우를 알면 됩니다.
this가 바뀌는 경우는 총 세가지가 있습니다.
1. 객체 메서드
const obj = {
	name: 'pkb',
    sayName() {
        console.log(this.name);
    }
};
obj.sayName(); // pkb 
- 객체 메서드 sayName안에서의 this는 객체를 가리킵니다. 이것은 객체의 메서드를 호출할 때this를 내부적으로 바꿔주기 때문입니다.
- 결과값이 달라지는 경우
const obj = {
	name: 'pkb',
    sayName() {
        console.log(this.name);
    }
};
const sayN = obj.sayName;
sayN() // window
2. 함수 메서드 bind, call, apply
function sayName() {
	console.log(this.name);
}
sayName(); // window
sayName.bind({name: 'pkb'})(); // pkb
sayName.apply({name: 'pkb'});// pkb
sayName.call({name: 'pkb'});// pkb
- 
    명시적으로 this를 바꾸는 함수 메서드bind,call,apply를 사용하면this가 객체를 가리킵니다.
- 
    bind를 쓸 때는 다시 호출해줘야 합니다.
- 
    call은 매개변수들을 순서대로 넣어줍니다.
- 
    apply는 매개변수들을 배열로 넣어줍니다.
// call 과 apply 차이
function add(a, b) { return a + b }
add.call(null, 3, 4); // 8
add.apply(null, [3, 5]); //8
3. 생성자 함수
function Person(name, age) {
  this.name = name;
  this.age = age;
}
Person.prototype.sayHi = function() {
  console.log(this.name, this.age);
}
const hero = new Person('Hero', 33); // Person {name: "Hero", age: 33}
hero.sayHi(); // Hero 33
- 이렇게 new를 붙이면this가 생성자를 통해 생성된 인스턴스(hero 자신)가 됩니다.
화살표 함수
- 부모함수의 this를 그대로 가져옵니다.
- 화살표함수는 call,bind,apply사용하지 못합니다.
- 화살표함수는 무조건 실행되게 되어있습니다.
const obj = {
    name: 'pkb',
    sayName: () => {
        console.log(this.name); // 여기서 sayName의 부모함수(스코프체인)는 annoymous
    }
}
obj.sayName(); // window
onst obj = {
    name: 'pkb',
    sayName() {
        console.log(this.name);
        const inner = () => {
            console.log(this.name);
        }
        inner();      //여기서 inner의 부모함수(스코프체인)는 sayName
    }
}
obj.sayName();
addEventListener에서의 this란
- addEventListener에서- this는 앞에 부분(객체)입니다. (외워야합니다.)
const header = document.querySelector("#content");
header.addEventListener('click', function() { // 여기서 function은 선언
	console.log(this); // header
}); 
- this는 호출할 때 결정나는데 위 코드에서는 호출이 보이지 않습니다.
- 즉, this를 알수가 없습니다. 하지만 이런 경우는 공식문서를 봐야하는데 공식문서에서 일반적으로 addEventListener의this는 앞에 부분(객체)가 된다고 되어있습니다.
- 만약 위 코드에서 화살표함수라면 this는window가 됩니다.
댓글남기기