22 this
22.1 this ํค์๋
this๋ ์์ ์ด ์ํ ๊ฐ์ฒด ๋๋ ์์ ์ด ์์ฑํ ์ธ์คํด์ค๋ฅผ ๊ฐ๋ฆฌํค๋ ์๊ธฐ ์ฐธ์กฐ ๋ณ์์ด๋ค.
์๋ฐ์คํฌ๋ฆฝํธ์ ํจ์๋ ํธ์ถ์ arguments ๊ฐ์ฒด์ this๋ฅผ ์๋ฌต์ ์ผ๋ก ์ ๋ฌ๋ฐ๋๋ค.
์๋ฐ์คํฌ๋ฆฝํธ์ this๋ java ๋ฑ์ this ํค์๋์ ๋ค๋ฅด๊ฒ ์๋ํ๋ค. java์์ this๋ ์ธ์คํด์ค ์์ ์ ๊ฐ๋ฆฌํค๋ ์ฐธ์กฐ๋ณ์์ด๋ค.
JS์ this๋ ํด๋น ํจ์ ํธ์ถ ๋ฐฉ์์ ๋ฐ๋ผ this์ ๋ฐ์ธ๋ฉ๋๋ ๊ฐ์ฒด๊ฐ ๋ฌ๋ผ์ง๋ค.
// ๊ฐ์ฒด ๋ฆฌํฐ๋ด
const circle = {
radius: 5,
getDiameter() {
// this๋ ๋ฉ์๋๋ฅผ ํธ์ถํ ๊ฐ์ฒด๋ฅผ ๊ฐ๋ฆฌํจ๋ค.
return 2 * this.radius;
}
};
console.log(circle.getDiameter()); // 10
๊ฐ์ฒด ๋ฆฌํฐ๋ด์ ๋ฉ์๋ ๋ด๋ถ์์๋ this๊ฐ ๋ฉ์๋๋ฅผ ํธ์ถํ ๊ฐ์ฒด, ์ฆ circle์ ๊ฐ๋ฆฌํจ๋ค.
// ์์ฑ์ ํจ์
function Circle(radius) {
// this๋ ์์ฑ์ ํจ์๊ฐ ์์ฑํ ์ธ์คํด์ค๋ฅผ ๊ฐ๋ฆฌํจ๋ค.
this.radius = radius;
}
Circle.prototype.getDiameter = function () {
// this๋ ์์ฑ์ ํจ์๊ฐ ์์ฑํ ์ธ์คํด์ค๋ฅผ ๊ฐ๋ฆฌํจ๋ค.
return 2 * this.radius;
};
// ์ธ์คํด์ค ์์ฑ
const circle = new Circle(5);
console.log(circle.getDiameter()); // 10
์์ฑ์ ํจ์ ๋ด๋ถ์ this๋ ์์ฑ์ ํจ์๊ฐ ์์ฑํ ์ธ์คํด์ค๋ฅผ ๊ฐ๋ฆฌํจ๋ค. ์ด์ฒ๋ผ this๋ ์ํฉ์ ๋ฐ๋ผ ๊ฐ๋ฆฌํค๋ ๋์์ด ๋ค๋ฅด๋ค.
this๋ ์ด๋์์๋ ์ฐธ์กฐ ๊ฐ๋ฅํ๋ค. ์ ์ญ์์๋ ํจ์ ๋ด๋ถ์์๋ ์ฐธ์กฐํ ์ ์๋ค.
// this๋ ์ด๋์๋ ์ง ์ฐธ์กฐ ๊ฐ๋ฅํ๋ค.
// ์ ์ญ์์ this๋ ์ ์ญ ๊ฐ์ฒด window๋ฅผ ๊ฐ๋ฆฌํจ๋ค.
console.log(this); // window
function square(number) {
// ์ผ๋ฐ ํจ์ ๋ด๋ถ์์ this๋ ์ ์ญ ๊ฐ์ฒด window๋ฅผ ๊ฐ๋ฆฌํจ๋ค.
console.log(this); // window
return number * number;
}
square(2);
const person = {
name: 'Lee',
getName() {
// ๋ฉ์๋ ๋ด๋ถ์์ this๋ ๋ฉ์๋๋ฅผ ํธ์ถํ ๊ฐ์ฒด๋ฅผ ๊ฐ๋ฆฌํจ๋ค.
console.log(this); // {name: "Lee", getName: ฦ}
return this.name;
}
};
console.log(person.getName()); // Lee
function Person(name) {
this.name = name;
// ์์ฑ์ ํจ์ ๋ด๋ถ์์ this๋ ์์ฑ์ ํจ์๊ฐ ์์ฑํ ์ธ์คํด์ค๋ฅผ ๊ฐ๋ฆฌํจ๋ค.
console.log(this); // Person {name: "Lee"}
}
const me = new Person('Lee');
ํ์ง๋ง this์ ๋ณธ ๋ชฉ์ ์ ์๋ ๊ฐ์ฒด์ ํ๋กํผํฐ๋ ๋ฉ์๋๋ฅผ ์ฐธ์กฐํ๊ธฐ ์ํจ์ด๋ฏ๋ก ๊ฐ์ฒด์ ๋ฉ์๋ ๋ด๋ถ, ์์ฑ์ ํจ์ ๋ด๋ถ์์๋ง ์๋ฏธ๊ฐ ์๋ค. ๋ฐ๋ผ์ strict mode๊ฐ ์ ์ฉ๋ ์ผ๋ฐ ํจ์ ๋ด๋ถ์ this์๋ undefined๊ฐ ๋ฐ์ธ๋ฉ๋๋ค. ์ผ๋ฐ ํจ์ ๋ด๋ถ์์ this๋ฅผ ์ฌ์ฉํ ํ์๊ฐ ์๊ธฐ ๋๋ฌธ์ด๋ค.
---
22.2 ํจ์ ํธ์ถ ๋ฐฉ์๊ณผ this ๋ฐ์ธ๋ฉ
Last updated
Was this helpful?