์๋ฐ์คํฌ๋ฆฝํธ์์ this๊ฐ ๋ฐ๋ผ๋ณด๋ ๋์์ ์คํ์ปจํ ์คํธ๊ฐ ์์ฑ๋ ๋, ์ฆ ํจ์๋ฅผ ํธ์ถํ ๋ ํธ์ถ ๋ฐฉ์์ ๋ฐ๋ผ ๊ฒฐ์ ๋ฉ๋๋ค.
๋ธ๋ผ์ฐ์ ํ๊ฒฝ์์ ์ ์ญ๊ฐ์ฒด๋ window
Node.js ํ๊ฒฝ์์ ์ ์ญ๊ฐ์ฒด๋ global
๋ฉ์๋ ํธ์ถ ์, ๋ฉ์๋ ๋ด๋ถ์ this๋ ํธ์ถํ ๊ฐ์ฒด๋ฅผ ๊ฐ๋ฆฌํต๋๋ค.
const obj = {
a: 2,
method1: function () {console.log(this)},
method2: function () {console.log(this.a)},
innerObj: {
method3: function () {
console.log(this);
},
},
};
obj.method1(); //obj
obj['method1'](); //obj
obj.method2(); //2
obj['method2'](); //2
obj.innerObj.method3(); //obj.innerObj
obj['innerObj']['method3'](); //obj.innerObj
์ผ๋ฐํจ์ ํธ์ถ์, ํจ์ ๋ด๋ถ์์์ this๋ ์ ์ญ๊ฐ์ฒด๋ฅผ ๊ฐ๋ฆฌํต๋๋ค.
const func = function() {console.log(this)};
func(); //์ ์ญ๊ฐ์ฒด
์๋์ผ๋ก ์ ์ญ๊ฐ์ฒด๋ฅผ ๋ฐ์ธ๋ฉํ์ง ์๊ณ ,
ํธ์ถ ๋น์ ์ฃผ๋ณํ๊ฒฝ์ this๋ฅผ ๊ทธ๋๋ก ์์๋ฐ๋ ๋ฐฉ๋ฒ์ค ํ๋๋ก
๋ณ์๋ฅผ ํ์ฉํ ์ ์์ต๋๋ค.
const obj = {
innerFunc : function() {
const self = this;
console.log(self);
},
}
obj.innerFunc(); //obj
ํ์ดํํจ์๋ ์คํ ์ปจํ ์คํธ๋ฅผ ์์ฑํ ๋, this๋ฐ์ธ๋ฉ์ด ๋์ง ์๊ณ ์์์ค์ฝํ์ this๋ฅผ ํ์ฉํ ์ ์์ต๋๋ค.
const obj = {
outer: function() {
console.log(this); //obj
const innerFunc = () => {
console.log(this);
};
innerFunc(); //obj (ํ์ดํํจ์์ด๋ฏ๋ก this๋ ์์์คํฌํฌ์ธ obj)
}
};
obj.outer();
๋ฉ์๋ ํธ์ถ ์ฃผ์ฒด์ธ ํจ์๋ฅผ ์ฆ์ ์คํํ๋๋ก ํ๋ ๋ช ๋ น์ด์ ๋๋ค.
const func = function(a,b,c) {
console.log(this, a,b,c);
};
func.call({x:1},2,3,4) // {x:1} 2 3 4
//call ๋ฉ์๋๋ฅผ ํธ์ถํ func๊ฐ ๋ฐ๋ก ์คํ๋๊ณ
//funcํจ์ ๋ด์ this๋ {x:1}์ ๋ฐ์ธ๋ฉ
call๋ฉ์๋์ ๊ธฐ๋ฅ์ ์ผ๋ก ๋์ผํฉ๋๋ค.
๋ค๋ง apply ๋ฉ์๋๋ ๋๋ฒ์งธ ์ธ์๋ฅผ ๋ฐฐ์ด๋ก ๋ฐ์ต๋๋ค.
const func = function(a,b,c) {
console.log(this, a,b,c);
};
func.apply({x:1},[2,3,4]) // {x:1} 2 3 4
call, apply ๊ธฐ๋ฅ๊ณผ ๋น์ทํ์ง๋ง ํจ์๋ฅผ ์ฆ์ ํธ์ถํ์ง ์์ต๋๋ค.
์ฒซ๋ฒ์งธ ์ธ์๋ก ๋ฐ์ thisArg ๋ฐ ์ธ์๋ค์ ๋ฐํ์ผ๋ก ์๋ก์ด ํจ์๋ฅผ ๋ฐํํ๋ ๋ฉ์๋์
๋๋ค.
const func = function(a,b,c) {
console.log(this, a,b,c);
};
const bindFunc1 = func.bind({x:1}); //this๋ฅผ {x:1}์ ๋ฐ์ธ๋ฉํ ํจ์๋ฅผ ๋ฐํ
bindFunc1(2,3,4); // {x:1} 2 3 4
const bindFunc2 = func.bind({x:1},7,8); //this๋ฅผ {x:1}์ ๋ฐ์ธ๋ฉ. ํ๊ณ ์์์๋ถํฐ ๋๊ฐ์ ์ธ์๋ฅผ 7,8๋ก ์ง์ ํ ํจ์๋ฅผ ๋ฐํ
bindFunc2(9); //{x:1} 7 8 9
์ฝ๋ฐฑํจ์๋ ํจ์์ด๊ธฐ ๋๋ฌธ์ this๋ ์ ์ญ๊ฐ์ฒด๋ฅผ ์ฐธ์กฐํฉ๋๋ค.
[3,4,5].forEach(function(x){console.log(this,x)});
//์ ์ญ๊ฐ์ฒด 3
//์ ์ญ๊ฐ์ฒด 4
//์ ์ญ๊ฐ์ฒด 5
const obj = {
arr: function() {
[3,4,5].forEach(function(x) {console.log(this,x)});
}
}
obj.arr();
//์ ์ญ๊ฐ์ฒด 3
//์ ์ญ๊ฐ์ฒด 4
//์ ์ญ๊ฐ์ฒด 5
์ฝ๋ฐฑํจ์๋ฅผ ์ธ์๋ก ๋ฐ๋ ๋ฉ์๋ ์ค ์ผ๋ถ๋ this๋ฅผ ๋ณ๋์ ์ธ์(thisArg)๋ก ์ง์ ํ ์ ์์ต๋๋ค.
thisArg๋ฅผ ๋ฐ๋ ๊ฒฝ์ฐ ์์ - forEach๋ฉ์๋
const obj = {
arr: function() {
[3,4,5].forEach(function(x) {console.log(this,x)},this);
}
}
obj.arr();
//obj 3
//obj 4
//obj 5