๐ This
์์ ์ด ์ํ ๊ฐ์ฒด ๋๋ ์์ ์ด ์์ฑํ ์ธ์คํด์ค๋ฅผ ๊ฐ๋ฆฌํค๋ ์๊ธฐ ์ฐธ์กฐ ๋ณ์
this๋ฅผ ํตํด ์์ ์ด ์ํ ๊ฐ์ฒด ๋๋ ์์ ์ด ์์ฑํ ์ธ์คํด์ค์ ํ๋กํผํฐ๋ ๋ฉ์๋๋ฅผ ์ฐธ์กฐํ ์ ์์ต๋๋ค.
this ๋ฐ์ธ๋ฉ์ ํจ์ ํธ์ถ ๋ฐฉ์์ ์ํด ๋์ ์ผ๋ก ๊ฒฐ์ ๋ฉ๋๋ค.
ํจ์ ํธ์ถ ๋ฐฉ์
1. ์ผ๋ฐ ํจ์
2. ๋ฉ์๋ ํธ์ถ
3. ์์ฑ์ ํจ์ ํธ์ถ
4. Function.prototype.apply/call/bind ๋ฉ์๋์ ์ํ ๊ฐ์ ํธ์ถ
5. ES6, ํ์ดํ ํจ์ ํธ์ถ
1. ์ผ๋ฐ ํจ์
์ผ๋ฐํจ์ ํธ์ถ this๋ ์ ์ญ ๊ฐ์ฒด์ธ window๋ฅผ ๊ฐ๋ฆฌํต๋๋ค.
-> ๊ฐ์ฒด๋ฅผ ์์ฑํ์ง ์๋ ์ผ๋ฐ ํจ์์์๋ this์ ์ฌ์ฉ์ ์๋ฏธ๊ฐ ์์ต๋๋ค
function normal(){
console.log(this); //Window
}
normal();
2. ๋ฉ์๋ ํธ์ถ
this๋ ๋ฉ์๋๋ฅผ ํธ์ถํ ๊ฐ์ฒด๋ฅผ ๊ฐ๋ฆฌํต๋๋ค.
const rectangle = {
width:10,
height:5,
getSize(){
console.log(this); //{width: 10, height: 5, getSize: ƒ}
return this.width*this.height;
}
}
console.log(rectangle.getSize()); //50
3. ์์ฑ์ ํจ์ ํธ์ถ
this๋ ์์ฑ์ ํจ์๊ฐ ์์ฑํ ์ธ์คํด์ค๋ฅผ ๊ฐ๋ฆฌํต๋๋ค.
function Rectangle(width, height){
this.width = width;
this.height = height;
}
const r1 = new Rectangle(10, 5);
console.log(r1); //Rectangle {width: 10, height: 5}
4. Function.prototype.apply/call/bind ๋ฉ์๋์ ์ํ ๊ฐ์ ํธ์ถ
ํจ์์ ์ฒซ ๋ฒ์งธ ์ธ์๋ก ์ ๋ฌํ๋ ๊ฐ์ฒด๊ฐ this์ ๋ฐ์ธ๋ฉ๋ฉ๋๋ค.
const rectangle = {
width : 10,
height : 5,
getSize(){
console.log(this);
// {width: 10, height: 5, getSize: ƒ}
function tmp(){
console.log(this)
};
tmp();
// window
// ์ผ๋ฐ ํจ์๋ก ํธ์ถ๋๊ธฐ ๋๋ฌธ์ this์ ์ ์ญ ๊ฐ์ฒด๊ฐ ๋ฐ์ธ๋ฉ๋ฉ๋๋ค.
setTimeout(tmp.bind(this), 0);
// {width: 10, height: 5, getSize: ƒ}
// Function.prototype.bind๋ฅผ ํตํด tmp์์ ์ฌ์ฉํ this๊ฐ์ฒด๋ฅผ ๋ฐ์ธ๋ฉ ํด์ค ์ ์์ต๋๋ค.
return this.width*this.height;
}
}
console.log(rectangle.getSize()); //50
ES6, ํ์ดํ ํจ์ ํธ์ถ
ํ์ดํ ํจ์ ๋ด์ this๋ ์์ ์ค์ฝํ์ this๋ฅผ ๊ฐ๋ฆฌํต๋๋ค.
ํ์ดํ ํจ์๋ ํจ์ ์์ฒด์ this ๋ฐ์ธ๋ฉ์ ๊ฐ์ง์ง ์์ต๋๋ค.
-> ์ฝ๋ฐฑ ํจ์ ๋ด๋ถ์์ this๊ฐ ์ ์ญ ๊ฐ์ฒด๋ฅผ ๊ฐ๋ฆฌํค๋ ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ๊ธฐ ์ํด ์์ฃผ ์ฌ์ฉํฉ๋๋ค.
const rectangle = {
width : 10,
height : 5,
getSize(){
setTimeout(()=>console.log(this), 0);
//{width: 10, height: 5, getSize: ƒ}
return this.width*this.height;
}
}
console.log(rectangle.getSize());
๐ก ํท๊ฐ๋ฆฌ์ง ๋ง์์ผ ํ๋ ๊ฒ
this ๋ฐ์ธ๋ฉ์ ํจ์ ํธ์ถ ์์ ์ ๊ฒฐ์ ๋๊ณ
๋ ์์ปฌ ์ค์ฝํ๋ ํจ์๊ฐ ์ ์ธ๋ ๋ ๊ฒฐ์ ๋ฉ๋๋ค.
'๐ป ํ๋ก ํธ์๋ > ๐ JS' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[์๋ฐ์คํฌ๋ฆฝํธ] ๋น๋๊ธฐ ์ฒ๋ฆฌ์ ์ด๋ฒคํธ๋ฃจํ (0) | 2023.12.27 |
---|---|
[์๋ฐ์คํฌ๋ฆฝํธ] ํด๋ก์ (1) | 2023.12.27 |
[์๋ฐ์คํฌ๋ฆฝํธ] ์คํ์ปจํ ์คํธ (0) | 2023.12.27 |
[์๋ฐ์คํฌ๋ฆฝํธ] ์ค์ฝํ (0) | 2023.12.27 |
๋ธ๋ผ์ฐ์ ๋ ๋๋ง ์๋ฆฌ (0) | 2023.12.27 |