728x90
๋ฐ์ํ
๐this
๋?
์๋ฐ์คํฌ๋ฆฝํธ์์ this๋ ํจ์๊ฐ ์ด๋ป๊ฒ ํธ์ถ๋์๋์ง์ ๋ฐ๋ผ ๋ฌ๋ผ์ง๋ ํน๋ณํ ํค์๋
์ฆ, ์ ์๋ ์์น๊ฐ ์๋๋ผ "ํธ์ถ๋ ๋ฐฉ์" ์ ๋ฐ๋ผ this๊ฐ ๊ฐ๋ฆฌํค๋ ๋์์ด ๋ฐ๋๋ค.
๐ ์ํฉ๋ณ this
์ ๋ฆฌ
1. ์ผ๋ฐ ํจ์ ํธ์ถ
function showThis() {
console.log(this);
}
showThis(); // ๋ธ๋ผ์ฐ์ ํ๊ฒฝ: window, strict ๋ชจ๋: undefined
- ์ผ๋ฐ ํจ์์์ this๋ ์ ์ญ ๊ฐ์ฒด(window) ๋ฅผ ๊ฐ๋ฆฌํจ๋ค.
- ๋จ, "use strict" ๋ชจ๋์์ undefined๊ฐ ๋๋ค.
2. ๊ฐ์ฒด์ ๋ฉ์๋๋ก ํธ์ถ
const user = {
name: 'Alice',
sayHi() {
console.log(this.name);
}
};
user.sayHi(); // "Alice"
- ๊ฐ์ฒด ์์์ ํจ์๋ฅผ ํธ์ถํ๋ฉด this๋ ๊ทธ ๊ฐ์ฒด ์์ ์ ๊ฐ๋ฆฌํจ๋ค.
3. ํ์ดํ ํจ์
const user = {
name: 'Bob',
sayHi: () => {
console.log(this.name);
}
};
user.sayHi(); // undefined (๋๋ ์ ์ญ name)
- ํ์ดํ ํจ์๋ ์์ ๋ง์ this๋ฅผ ๊ฐ์ง์ง ์๋๋ค.
- ์ ์๋ ์์ ์ ์ธ๋ถ ์ค์ฝํ์ this๋ฅผ ๊ทธ๋๋ก ์ฌ์ฉํ๋ค.
4. ์์ ๋น๊ต
const name = "์ ์ญ ์ด๋ฆ";
const user = {
name: "๊ฐ์ฒด ์ด๋ฆ",
sayHi1: function () {
console.log("sayHi1:", this.name);
},
sayHi2: () => {
console.log("sayHi2:", this.name);
}
};
user.sayHi1(); // "sayHi1: ๊ฐ์ฒด ์ด๋ฆ"
user.sayHi2(); // "sayHi2: ์ ์ญ ์ด๋ฆ"
- sayHi1: ์ผ๋ฐ ํจ์ → this๋ ํธ์ถํ ๊ฐ์ฒด user
- sayHi2: ํ์ดํ ํจ์ → this๋ ์ธ๋ถ ์ค์ฝํ(์ ์ญ)
5. setTimeout๊ณผ this
const user = {
age: 25,
getAge() {
console.log(this.age);
}
};
setTimeout(user.getAge, 1000); // undefined
setTimeout์ user.getAge๋ฅผ ์ผ๋ฐ ํจ์์ฒ๋ผ ํธ์ถํด์ this๊ฐ ๋ฐ๋
ํด๊ฒฐ๋ฐฉ๋ฒ
setTimeout(() => user.getAge(), 1000); // 25
setTimeout(user.getAge.bind(user), 1000); // 25
6. ํจ์ ์ธ๋ถ์์ ํ ๋นํ ๊ฒฝ์ฐ
function hello() {
console.log("hello", this);
}
const obj = {
say: hello
};
obj.say(); // obj
hello(); // window (or undefined in strict mode)
728x90
๋ฐ์ํ
'๐งก JavaScript' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[JS] JavaScript ์์ฑ ๋ฐ ๋ฉ์๋ (1) | 2025.04.27 |
---|---|
[JS/ํธ๋ฌ๋ธ์ํ ] 404 ์ค๋ฅ ํด๊ฒฐํ๊ธฐ(Failed to load resource: ~ ) (0) | 2025.04.02 |
[JS] ๋ณ์(Variable) (1) | 2025.03.18 |
[JS] ํํ์๊ณผ ๋ฌธ (0) | 2025.02.19 |
[JS] ๋ฐ์ดํฐํ์ (Data Type) (0) | 2025.02.14 |