Lexical this๋ ํ์ดํ ํจ์๊ฐ ์์ ๋ง์ this๋ฅผ ์์ฑํ์ง ์๊ณ , ์์ ์ ๊ฐ์ธ๋ ์ธ๋ถ ์ค์ฝํ์ this๋ฅผ ๊ทธ๋๋ก ์ฌ์ฉํ๋ ๊ฒ์ ์๋ฏธํ๋ค.
์ผ๋ฐ ํจ์ vs ํ์ดํ ํจ์
์ผ๋ฐ ํจ์์ this
- ํธ์ถ ๋ฐฉ์์ ๋ฐ๋ผ this๊ฐ ๋์ ์ผ๋ก ๊ฒฐ์ ๋จ
- ํจ์๊ฐ ์ด๋ป๊ฒ ํธ์ถ๋์๋์ง๊ฐ ์ค์
const user = {
name: "John",
greet: function() {
console.log(`Hello, ${this.name}`);
}
};
user.greet(); // "Hello, John"
const greet = user.greet;
greet(); // "Hello, undefined" (this๊ฐ ์ ์ญ ๊ฐ์ฒด๋ฅผ ๊ฐ๋ฆฌํด)ํ์ดํ ํจ์์ this (Lexical this)
- ํจ์๊ฐ ์ ์ธ๋ ์์น์ this๋ฅผ ์ฌ์ฉ
- ํธ์ถ ๋ฐฉ์๊ณผ ๊ด๊ณ์์ด this๊ฐ ๊ณ ์ ๋จ
const user = {
name: "John",
greet: () => {
console.log(`Hello, ${this.name}`);
}
};
user.greet(); // this๋ user๊ฐ ์๋ ์ธ๋ถ ์ค์ฝํ์ this๋ฅผ ๊ฐ๋ฆฌํด์ค์ ํ์ฉ ์ฌ๋ก
ํด๋์ค ๋ฉ์๋์์์ ์ฝ๋ฐฑ
// ๋ฌธ์ ๊ฐ ์๋ ์ฝ๋
class Counter {
constructor() {
this.count = 0;
}
start() {
setInterval(function() {
// this๊ฐ ์ ์ญ ๊ฐ์ฒด๋ฅผ ๊ฐ๋ฆฌ์ผ์ ์๋ํ ๋๋ก ๋์ํ์ง ์์
this.count++;
console.log(this.count);
}, 1000);
}
}
// ํ์ดํ ํจ์๋ก ํด๊ฒฐ
class Counter {
constructor() {
this.count = 0;
}
start() {
setInterval(() => {
// this๊ฐ Counter ์ธ์คํด์ค๋ฅผ ๊ฐ๋ฆฌํด
this.count++;
console.log(this.count);
}, 1000);
}
}์ด๋ฒคํธ ํธ๋ค๋ฌ
// ๋ฌธ์ ๊ฐ ์๋ ์ฝ๋
class App {
constructor() {
this.buttonClicks = 0;
this.button = document.querySelector('button');
this.button.addEventListener('click', function() {
// this๊ฐ ๋ฒํผ ์๋ฆฌ๋จผํธ๋ฅผ ๊ฐ๋ฆฌํด
this.buttonClicks++; // ์๋ฌ!
});
}
}
// ํ์ดํ ํจ์๋ก ํด๊ฒฐ
class App {
constructor() {
this.buttonClicks = 0;
this.button = document.querySelector('button');
this.button.addEventListener('click', () => {
// this๊ฐ App ์ธ์คํด์ค๋ฅผ ๊ฐ๋ฆฌํด
this.buttonClicks++;
});
}
}Lexical this๊ฐ ์ ์ฉํ ์ํฉ
- ๋น๋๊ธฐ ์ฝ๋ฐฑ
class DataFetcher {
constructor() {
this.data = null;
}
fetch() {
setTimeout(() => {
// this๊ฐ DataFetcher ์ธ์คํด์ค๋ฅผ ์ฌ๋ฐ๋ฅด๊ฒ ๊ฐ๋ฆฌํด
this.data = "fetched data";
console.log(this.data);
}, 1000);
}
}- ๋ฉ์๋ ์ฒด์ด๋
class Builder {
constructor() {
this.items = [];
}
addItem(item) {
// ํ์ดํ ํจ์๋ก ์ธํด this๊ฐ Builder ์ธ์คํด์ค๋ฅผ ๊ฐ๋ฆฌํด
process.nextTick(() => {
this.items.push(item);
console.log(this.items);
});
return this;
}
}์ฃผ์์ฌํญ
- ๊ฐ์ฒด์ ๋ฉ์๋๋ก ๋ถ์ ์ ํ ๊ฒฝ์ฐ
// ์๋ชป๋ ์ฌ์ฉ
const obj = {
name: "John",
greet: () => {
console.log(`Hello, ${this.name}`);
}
};
// ์ฌ๋ฐ๋ฅธ ์ฌ์ฉ
const obj = {
name: "John",
greet() {
console.log(`Hello, ${this.name}`);
}
};๊ฐ์ฒด ๋ฉ์๋์์ ์ผ๋ฐ ํจ์์ ํ์ดํ ํจ์์ ์ฐจ์ด
- ํ๋กํ ํ์ ๋ฉ์๋๋ก ๋ถ์ ์ ํ ๊ฒฝ์ฐ
// ํผํด์ผ ํ ์ฌ์ฉ
Function.prototype.myBind = () => {
console.log(this); // ์๋ชป๋ this ๋ฐ์ธ๋ฉ
};
// ์ฌ๋ฐ๋ฅธ ์ฌ์ฉ
Function.prototype.myBind = function() {
console.log(this); // ์ ์์ ์ธ this ๋ฐ์ธ๋ฉ
};์ ๋ฆฌ
-
Lexical this์ ํต์ฌ
- ํ์ดํ ํจ์๋ ์์ ์ this๋ฅผ ์์ฑํ์ง ์์
- ์ ์ธ๋ ์์น์ this๋ฅผ ๊ทธ๋๋ก ์ฌ์ฉ
- ํธ์ถ ๋ฐฉ์์ ๊ด๊ณ์์ด this๊ฐ ์ ์ง๋จ
-
์ฌ์ฉํ๋ฉด ์ข์ ๊ฒฝ์ฐ
- ์ฝ๋ฐฑ ํจ์
- ์ด๋ฒคํธ ํธ๋ค๋ฌ
- ๋น๋๊ธฐ ํจ์
- ์ค์ฒฉ ํจ์
-
ํผํด์ผ ํ ๊ฒฝ์ฐ
- ๊ฐ์ฒด์ ๋ฉ์๋
- ํ๋กํ ํ์ ๋ฉ์๋
- this๋ฅผ ๋์ ์ผ๋ก ๋ฐ์ธ๋ฉํด์ผ ํ๋ ๊ฒฝ์ฐ