์๋ฐ์คํฌ๋ฆฝํธ์์ ๋ชจ๋ ํจ์๋ ์คํ๋ ๋๋ง๋ค ํจ์ ๋ด๋ถ์ย this
๋ผ๋ ๊ฐ์ฒด๊ฐ ์ถ๊ฐ๋๋ค.ย ๊ทธ๋ ๊ธฐ ๋๋ฌธ์ย this
๋ ํจ์๊ฐ ์ด๋ป๊ฒ ํธ์ถ๋์๋์ง์ ๋ฐ๋ผ ๋ค๋ฅด๊ฒ ๋ฐ์ธ๋ฉ๋๋ค.
1. ๊ฐ์ฒด์ ๋ฉ์๋๋ก ํธ์ถํ ๊ฒฝ์ฐ (A.b ํํ) ํด๋น ๋ฉ์๋๋ฅผ ํธ์ถํ ๊ฐ์ฒด๋ก ๋ฐ์ธ๋ฉ๋๋ค.
const obj = {
value: 1,
printValue: function () {
console.log(this);
},
};
obj.printValue();
// {value: 1, printValue: f}
// obj๊ฐ printValue๋ฅผ ํธ์ถํ๊ธฐ ๋๋ฌธ
const obj = {
value: 1,
printValue: function () {
console.log(this);
},
};
const obj2 = {
value: 2,
printValue: obj.printValue,
};
obj2.printValue();
// {value: 2, printValue: f}
// obj2๊ฐ ํธ์ถํ๊ธฐ ๋๋ฌธ
const obj = {
value: 1,
printValue: function () {
console.log(this);
},
};
const global = obj.printValue;
global();
// window ๊ฐ์ฒด
// globalํจ์๊ฐ ํธ์ถ๋ ๋ A.b์ ํํ๋ก ํธ์ถ๋์ง ์๊ณ , window ๊ฐ์ฒด๊ฐ ํธ์ถํ๊ธฐ ๋๋ฌธ
const obj = {
value: 1,
printValue: function () {
const innerFunc = function () {
console.log(this);
};
innerFunc();
},
};
obj.printValue();
// window ๊ฐ์ฒด
// innerFunc ํจ์๊ฐ ํธ์ถ๋ ๋ A.b์ ํํ๋ก ํธ์ถ๋์ง ์๊ณ , window ๊ฐ์ฒด๊ฐ ํธ์ถํ๊ธฐ ๋๋ฌธ
3. ES5์์ ์ถ๊ฐ๋ call
, apply
, bind
์ ๊ฐ์ ๋ฉ์๋๋ฅผ ํ์ฉํ๋ฉด, ํจ์๋ฅผ ์ด๋ป๊ฒ ํธ์ถํ๋์ง์ ์๊ด ์์ด ์ง์ this
๋ฅผ ์ค์ ํ ์ ์๋ค.
const func = function () {
console.log(this);
};
const obj = {
value: 1,
};
func.call(obj); // {value: 1}
func.apply(obj); // {value: 1}
func.bind(obj)(); // {value: 1}
const obj = {
value: 1,
printValue: function () {
const innerFunc = () => {
console.log(this);
};
innerFunc();
},
};
obj.printValue();
// {value: 1, printValue: f}
// ํ์ดํ ํจ์์์์ this๋ ํจ์๊ฐ ์ํด์๋ ๊ณณ์ ์์ this๋ฅผ ๊ณ์น๋ฐ๊ธฐ ๋๋ฌธ
ํ์ดํ ํจ์๋ย call
,ย bind
,ย apply
๋ฅผ ์ฌ์ฉํ์ฌย this
์ ๊ฐ์ ์ ํ ์ ์๋ค.
5. new
ํค์๋๋ฅผ ํตํด ์์ฑ์ ํจ์๋ฅผ ํธ์ถํ ๊ฒฝ์ฐ, this๋ ์์ฑ๋ ๊ฐ์ฒด์ธ ์์ ์ด ๋๋ค.
function Func(value) {
this.value = value;
this.printValue = function () {
console.log(this);
};
}
let a = new Func(2);
a.printValue();
// Funcย {value: 2, printValue: ฦ}
-
this๋ฅผ ์์ธก ๊ฐ๋ฅํ๊ฒ ์ฌ์ฉํ๊ธฐ ์ํด์ ์ผ๋ฐ ํจ์์ this ๋ฐ์ธ๋ฉ ๋ฉ์๋๋ฅผ ํจ๊ป ์ฌ์ฉํ๋ค.
-
ํจ์ ๋ด๋ถ์ ํจ์์์ this๋ฅผ ์ฌ์ฉํ ๋๋ ์์์ this๋ฅผ ํจ๊ป ์ฌ์ฉํ๋ ๊ฒฝ์ฐ๊ฐ ๋ง๊ธฐ ๋๋ฌธ์ ํ์ดํ ํจ์๋ฅผ ์ฌ์ฉํ๊ธฐ๋ ํ๋ค.