-
Notifications
You must be signed in to change notification settings - Fork 1
Open
Description
This (์ด๊ฒ)
- JS์์ this๋ ๋ค๋ฅธ ์ธ์ด๋ค๊ณผ ๋ค๋ฅด๊ฒ ์ฌ์ฉ๋๋ค๊ณ ํ๋ค. ๋ฌธ๋งฅ์ ๋ฐ๋ผ ์ด๊ฒ์ด ๊ฐ๋ฆฌํค๋ ๊ฒ์ด ๋ฌ๋ผ์ง๋ค.
- this๋ ๋ด๊ฐ ์์ผ๋ก ๋ง๋ค์ด์ง ์ธ์คํด์ค๋, ๊ฐ์ฒด ์๊ธฐ ์์ ์ ๊ฐ๋ฆฌํค๋ ์ฉ๋๋ก ์ฌ์ฉ๋๋ค. ํน์ ํ ๊ฐ์ฒด์ this๋ฅผ ๋ฌถ์ด๋์ ๊ฒ์ this ๋ฐ์ธ๋ฉ์ด๋ผ๊ณ ์นญํ๋ค. ์๋ฐ๋ C์์์ this๋ ํ๋์ ์ธ์คํด์ค์ ๊ณ ์ ๋์ง๋ง ์๋ฐ์คํฌ๋ฆฝํธ ๋๋ ํ์ ์คํฌ๋ฆฝํธ๋ ๋ฐํ์ ์์์ this ๋ฐ์ธ๋ฉ์ด ๋์ ์ผ๋ก ๊ฒฐ์ ๋๋ค.
๊ธ๋ก๋ฒ ์ปจํ ์คํธ์์์ this๋?
- ๋ธ๋ผ์ฐ์ : this = window ๋ค.
- ๋
ธ๋ : ๋ชจ๋์ ๊ฐ๋ฆฌํต๋๋ค. ์ฝ์๋ก๊ทธ์ ๋
ธ๋์ this๋ฅผ ์ถ๋ ฅํ๋ฉด ํ
ํ
๋น ๊ฐ์ฒด๊ฐ ์ถ๋ ฅ์ด ๋๋ค.
globalThis๋ฅผ ์ถ๋ ฅํ๋ฉด ๋ ธ๋์์ ์ฌ์ฉ๋๋ ์ ์ญ ๊ฐ์ฒด๋ค์ด ์ถ๋ ฅ๋๋ค.
ex) setTimeout, setInterver ๊ฐ์ ๊ฒ๋ค. globalThis๋ ์๋ต์ด ๊ฐ๋ฅํ๋ค.
๋ธ๋ผ์ฐ์ ์์์ this๋ window๋ค.
ํจ์ ๋ด๋ถ์์์ this
function fun() {
console.log(this);
}
fun();
use stric = ์๊ฒฉ๋ชจ๋๋ฅผ ์ฌ์ฉํ๊ฒ ๋ ๊ฒฝ์ฐ, undefined๊ฐ ๋ฌ๋ค.
๋์จํ ๋ชจ๋์์๋ globalThis๋ฅผ ๊ฐ๋ฆฌํค๋ ๊ฒ์ ํ์ธํด๋ณผ ์ ์๋ค.
์์ฑ์ ํจ์ ๋๋ ํด๋์ค์์์ this, ์์ผ๋ก ์์ฑ๋ ์ธ์คํด์ค ์์ฒด๋ฅผ ๊ฐ๋ฆฌํด
// ์ด ์์ฑ์ ํจ์ ์์์
function Cat(name) {
this.name = name;
// ์์ผ๋ก ๋ง๋ค์ด์ง ์ค๋ธ์ ํธ ๊ทธ ์์ฒด๋ฅผ ๊ฐ๋ฆฌํจ๋ค๊ณ ๋ณด๋ฉด ๋๋ค.
this.printName = function() {
console.log(this.name);
}
}
const cat1 = new Cat('๋์น');
const cat2 = new Cat('๋ซ์น');
cat1.printName();
cat2.printName();
Metadata
Metadata
Assignees
Labels
No labels