this 마지막 정리를 해본다
1. 전역공간에서 this를 호출했을 때 : 전역공간에서 this는 처음부터 호출이 되기 때문에 값이 정해져있다.
2. call(), apply(), bind() 메서드 : 명시적인 this binding
let func = function(a, b, c) {
console.log(this, a, b, c);
}
func(1, 2, 3); // window{..} 1 2 3
func.call({ x : 1 }, 4, 5, 6 ); // {x: 1} 4 5 6
func.call({ x: 1, y:2}, 6, 7, 8);
let func = function(a, b, c) {
console.log(this, a, b, c);
}
func.apply({x:1}, [4, 5, 6]); // {x: 1} 4 5 6
let func = function (a, b, c, d) {
console.log(this, a, b, c, d);
};
func(1, 2, 3, 4); // Window {…} 1 2 3 4
let bindFunc1 = func.bind({ x: 1 });
bindFunc1(5, 6, 7, 8); // {x: 1} 5 6 7 8
let bindFunc2 = func.bind({ x: 1 }, 4, 5);
bindFunc2(9, 10); // {x: 1} 4 5 9 10
1. 함수 호출시 : 함수를 호출했을 때 함수 내부에서 this는 어떻게 될까?
(1) ES5 : 함수 내부의 this는 언제나 전역 객체를 가리킨다(암기)
function a () {
console.log(this);
}
a(); // window
>> 함수 a()을 호출하는 순간에 전역공간에서 호출한 것이다.
누가 호출한 것? 호출한 대상이 전역객체가 되는 것.
function b () {
console.log(this);
function c () {
console.log(this);
}
c(); >> 호출한 주체가 b()일 것 같은데, c()도 값이 전역 객체로 출력된다.
}
b(); // window, window
let d = {
e : function() {
function f() {
console.log(this);
}
f(); // window (함수로써 호출했기 때문에 전역객체)
}
}
d.e();
>>>
(2) ES6 : arrow funcion
2. 메서드 호출시 : 메서드를 호출한 주체(메서드명 앞)를 보면 된다. 메서드 명의 '점' 바로 앞에 있는 애가 this가 된다.
let a = {
b : function() {
console.log(this);
}
}
a.b();
> a : this
b() : 메서드
let a = {
b : {
c : function() {
console.log(this);
}
}
}
a.b.c();
> a.b : this
c() : 메서드
obj.func();
obj['func']();
person.info.getName();
person.info['getName']();
person['info'].getName();
person['info']['getName']();
3. 생성자함수 호출시 (new 연산자를 썼을 때)
function Person(n, a) {
this.name = n;
this.age = a;
}
let roy = Person('재남', 30);
console.log(window.name, window.age); // 재남 30
-> new 연산자 없이 함수로 Person을 출력하면 전역객체.name, 전역객체.age
let roy = new Person('재남', 30);
console.log(roy);
-> new를 넣은 채로 호출하면 생성자 함수로서 호출한 거니까 roy라고 하는 이 변수 새로 생성될 person의 인스턴스 객체자신이 this가 되니까 this.name에 재남, this.age 30