๋ฐฐ๊ฒฝ
๐ก js์์ this๋,
์์ ์ด ์ํ ๊ฐ์ฒด ๋๋ ์์ ์ด ์์ฑํ ์ธ์คํด์ค๋ฅผ ๊ฐ๋ฆฌํค๋ ์๊ธฐ ์ฐธ์กฐ ๋ณ์(self-referencing variable)์ ๋๋ค.
์ด this๋, ํจ์๊ฐ ํธ์ถ๋๋ฉด arguments๊ฐ์ฒด์ this๊ฐ ์๋ฌต์ ์ผ๋ก ํจ์ ๋ด๋ถ์ ์ ๋ฌ๋๋ฉด์ ๋ง๋ค์ด์ง๊ฒ ๋ฉ๋๋ค. ํ์ง๋ง ํจ์ ํธ์ถ๋ฐฉ์์ ๋ฐ๋ผ์ this์ ๋ฐ์ธ๋ฉ๋๋ ๊ฐ์ฒด๋ ๋์ ์ผ๋ก ๊ฒฐ์ ๋ฉ๋๋ค.
const foo = function() {
console.dir(this);
};
// 1. ์ผ๋ฐํจ์ ํธ์ถ
// foo๋ด๋ถ์ this๋ window๋ฅผ ๊ฐ๋ฆฌํค๊ฒ ๋๋ค
foo(); // window
// 2. ๋ฉ์๋๋ก์ ํธ์ถ
// ๋ฉ์๋๋ก ํธ์ถํ๊ธฐ ์ํด, ํ ๊ฐ์ฒด์ property๊ฐ์ผ๋ก ํจ์๋ฅผ ํ ๋น
// foo๋ด๋ถ์์ this๋ ๋ฉ์๋๋ฅผ ํ๋กํผํฐ๋ก ๊ฐ์ง๋ฉด์, ํธ์ถํ ๊ฐ์ฒด obj๋ฅผ ๊ฐ๋ฆฌํค๊ฒ ๋๋ค
const obj = { foo : foo};
obj.foo(); // obj
// 3. ์์ฑ์ ํจ์๋ก์ ํธ์ถํ๊ธฐ
// ํจ์๋ฅผ new์ฐ์ฐ์๋ฅผ ์ฌ์ฉํด์ ์์ฑ์ ํจ์๋ก์ ํธ์ถํ๋ค
// foo๋ด๋ถ์ this๋, ์ด ์์ฑ์ ํจ์๊ฐ ๋ง๋ค์ด๋ธ ์ธ์คํด์ค๋ฅผ ๊ฐ๋ฆฌํค๊ฒ ๋๋ค
new foo();
// 4. apply/call/bind๋ฉ์๋
// ์ด๋๋, ์ข ๋ ์ต์ํ๊ฒ ์๊ณ ์๋ ๋ฐฉ์!
// foo๋ด๋ถ์ this๋, ์ ๋ฌ๋ฐ์ ์ธ์์ ์ํด์ ๊ฒฐ์ ๋๋ค
const bar = {name: 'bar'};
foo.call(bar);
foo.apply(bar);
foo.bind(bar)();
๋ฐฐ๊ฒฝ
- js์์ ์ ์ญ๊ฐ์ฒด๋ ๋ชจ๋ ๊ฐ์ฒด์ ์ ์ผํ ์ต์์ ๊ฐ์ฒด๋ฅผ ์๋ฏธํ๋ ๊ฒ์ผ๋ก, ์ ์ญ์ค์ฝํ๋ฅผ ๊ฐ๋ ์ ์ญ๋ณ์๋ฅผ property๋ก ์์ ํ๊ฒ ๋ฉ๋๋ค.
- Browser-side โ window
- Server-side โ global
this๊ฐ ๊ธฐ๋ณธ์ ์ผ๋ก ๋ฐ์ธ๋ฉ๋๋ ๊ฐ์ฒด๋?
- ์ ์ญํจ์๋ ๋ฌผ๋ก
- ์ ์ญํจ์์์ ๋ด๋ถํจ์๋
- ๋ฉ์๋์ ๋ด๋ถํจ์์ผ ๋๋
- ์ฝ๋ฐฑํจ์์ ๊ฒฝ์ฐ๊น์ง ..
// ๋ฉ์๋์ ๋ด๋ถํจ์์ธ ๊ฒฝ์ฐ
var value = 1;
var obj = {
value: 100,
foo: function() {
console.log("foo's this: ", this); // obj
console.log("foo's this.value: ", this.value); // 100
**function bar() {
console.log("bar's this: ", this); // window
console.log("bar's this.value: ", this.value); // 1
}**
bar();
}
};
obj.foo();
๐ ๋ด๋ถํจ์๋ ์ผ๋ฐ ํจ์, ๋ฉ์๋, ์ฝ๋ฐฑํจ์ ์ด๋์์ ์ ์ธ๋์๋ ๊ด๊ฒ์์ด this๋ ์ ์ญ๊ฐ์ฒด์ ๋ฐ์ธ๋ฉ๋๋ค
var value = 1;
const obj= {
value : 100,
foo() {
// this์ ๋ฐ์ธ๋ฉ๋ ๊ฐ์ฒด(obj)๋ฅผ, ๋ณ์๋ฅผ ๋ง๋ค์ด์ ํ ๋นํด๋ณด์
const that = this;
// ๋ด๋ถ ๋ฉ์๋์์ ํ์ฉํ๊ธฐ
setTimeout(function() {
console.log(that.value); // 100
}, 100);
}
};
obj.foo();
var value = 1;
const obj = {
value: 100,
foo() {
// ์ฝ๋ฐฑ ํจ์์ ๋ช
์์ ์ผ๋ก this๋ฅผ ๋ฐ์ธ๋ฉํ๋ค.
**setTimeout(function () {
console.log(this.value); // 100
}.bind(this), 100);**
}
};
obj.foo();
var value = 1;
const obj = {
value: 100,
foo() {
**// ํ์ดํ ํจ์ ๋ด๋ถ์ this๋ ์์ ์ค์ฝํ์ this๋ฅผ ๊ฐ๋ฆฌํจ๋ค.**
setTimeout(() => console.log(this.value), 100); // 100
}
};
obj.foo();
๐ js์์ this๋, ์์ ์ด ์ํ ๊ฐ์ฒด ๋๋ ์์ ์ด ์์ฑํ ์ธ์คํด์ค๋ฅผ ๊ฐ๋ฆฌํค๋ ์๊ธฐ ์ฐธ์กฐ ๋ณ์(self-referencing variable)์ ๋๋ค.
์ด this๋, ํจ์๊ฐ ํธ์ถ๋๋ฉด arguments๊ฐ์ฒด์ this๊ฐ ์๋ฌต์ ์ผ๋ก ํจ์ ๋ด๋ถ์ ์ ๋ฌ๋๋ฉด์ ๋ง๋ค์ด์ง๊ฒ ๋ฉ๋๋ค. ํ์ง๋ง ํจ์ ํธ์ถ๋ฐฉ์์ ๋ฐ๋ผ์ this์ ๋ฐ์ธ๋ฉ๋๋ ๊ฐ์ฒด๋ ๋์ ์ผ๋ก ๊ฒฐ์ ๋ฉ๋๋ค.this์ ๋ฐ์ธ๋ฉ์ ๊ด์ฌํ๋ ํจ์ํธ์ถ ๋ฐฉ์์๋ ํจ์ํธ์ถ, ๋ฉ์๋ ํธ์ถ, ์์ฑ์ ํจ์ํธ์ถ, apply/call/bind๋ฉ์๋์ ์ํ ๊ฐ์ ํธ์ถ ๋ฐฉ์์ด ์์ต๋๋ค.
์ผ๋ฐ์ ์ธ ํจ์ ํธ์ถ์ ๊ฒฝ์ฐ, this์๋ ๊ธฐ๋ณธ์ ์ผ๋ก ์ ์ญ๊ฐ์ฒด๊ฐ ๋ฐ์ธ๋ฉ๋๊ฒ ๋ฉ๋๋ค. ๊ทธ๋์ this๊ฐ ์ ์ญ๊ฐ์ฒด๋ฅผ ์ฐธ์กฐํ๋ ๊ฒ์ ํผํ๊ธฐ ์ํด, ๋ฉ์๋ ์์์์ const๋ณ์๋ฅผ ํ์ฉํด this๋ฅผ ๋ฐ์ธ๋ฉํด๋๊ณ , ๋ฉ์๋๋ด์์ ์ฐธ์กฐํ๋ ๋ฐฉ๋ฒ์ด ์์ต๋๋ค. ๊ทธ ๋ฐ์๋, Function๊ฐ์ฒด์ apply, call, bind๋ฉ์๋์ ํ์ดํ ํจ์๋ฅผ ํ์ฉํด์๋ ์๋์ฐธ์กฐ๋ฅผ ํผํ ์ ์์ต๋๋ค.