์๋ฐ์คํฌ๋ฆฝํธ์ this: ๊ฐ๋ , ํ์ฉ, ์ฅ๋จ์ , ์์ ์ฝ๋
this๋?
์๋ฐ์คํฌ๋ฆฝํธ์์ this
๋ ํจ์๊ฐ ์ด๋ป๊ฒ ํธ์ถ๋๋์ง์ ๋ฐ๋ผ ๋์ ์ผ๋ก ๋ฐ์ธ๋ฉ๋๋ ํน๋ณํ ํค์๋์
๋๋ค. this
๋ ํจ์ ๋ด์์ ํ์ฌ ์คํ ์ค์ธ ์ปจํ
์คํธ๋ฅผ ์ฐธ์กฐํ๋ฉฐ, ํธ์ถ ๋ฐฉ์์ ๋ฐ๋ผ ๋ค๋ฅด๊ฒ ๋์ํฉ๋๋ค.
์ญํ
this
์ ์ฃผ๋ ์ญํ ์ ๋ค์๊ณผ ๊ฐ์ต๋๋ค.
- ๊ฐ์ฒด์ ์์ฑ ์ฐธ์กฐ: ๋ฉ์๋ ๋ด์์ ๊ฐ์ฒด์ ์์ฑ์ ์ ๊ทผํ๊ธฐ ์ํด ์ฌ์ฉ๋ฉ๋๋ค.
- ์์ฑ์ ํจ์: ์์ฑ์ ํจ์์์ ๊ฐ์ฒด๋ฅผ ์์ฑํ ๋, ์๋ก์ด ์ธ์คํด์ค๋ฅผ ๊ฐ๋ฆฌํต๋๋ค.
- ์ด๋ฒคํธ ํธ๋ค๋ฌ: ์ด๋ฒคํธ ํธ๋ค๋ฌ ํจ์ ๋ด์์ ์ด๋ฒคํธ๊ฐ ๋ฐ์ํ ์์๋ฅผ ์ฐธ์กฐํฉ๋๋ค.
์ฌ์ฉ ์ํฉ
1. ๊ฐ์ฒด์ ๋ฉ์๋์์
const obj = {
name: 'MyObject',
logName: function() {
console.log(this.name);
}
};
obj.logName(); // ์ถ๋ ฅ: MyObject
2. ์์ฑ์ ํจ์์์
function Person(name) {
this.name = name;
}
const person1 = new Person('Alice');
console.log(person1.name); // ์ถ๋ ฅ: Alice
3. ์ด๋ฒคํธ ํธ๋ค๋ฌ์์
const button = document.getElementById('myButton');
button.addEventListener('click', function() {
console.log(this); // ์ถ๋ ฅ: <button id="myButton">Click me</button>
});
์ฅ๋จ์
์ฅ์
- ์ ์ฐํ ํ์ฉ: ๋ค์ํ ์ํฉ์์ ๋์ ์ผ๋ก ์ปจํ ์คํธ์ ๋ฐ์ธ๋ฉ๋์ด ์ ์ฐํ๊ฒ ํ์ฉ ๊ฐ๋ฅํฉ๋๋ค.
- ์ฌ์ฌ์ฉ์ฑ: ํจ์๋ฅผ ์ฌ๋ฌ ์ปจํ ์คํธ์์ ์ฌ์ฉํ ์ ์๋๋ก ๋์์ค๋๋ค.
๋จ์
- ํผ๋์ ์ฌ์ง: ์ฝ๋๊ฐ ๋ณต์กํด์ง ๊ฒฝ์ฐ,
this
๊ฐ ์ด๋ค ๊ฐ์ ์ฐธ์กฐํ๋์ง ํผ๋์ด ๋ฐ์ํ ์ ์์ต๋๋ค. - Arrow Function๊ณผ ์ฐจ์ด: Arrow Function์ ์์ฒด์ ์ธ
this
๋ฅผ ๊ฐ์ง์ง ์๊ธฐ ๋๋ฌธ์, ์ฌ์ฉ ์ ์ฃผ์๊ฐ ํ์ํฉ๋๋ค.
์์ ์ฝ๋
1. ๊ฐ์ฒด์ ๋ฉ์๋์์์ this ํ์ฉ
const calculator = {
value: 0,
add: function(num) {
this.value += num;
}
};
calculator.add(5);
console.log(calculator.value); // ์ถ๋ ฅ: 5
2. ์์ฑ์ ํจ์์์์ this ํ์ฉ
function Car(model) {
this.model = model;
}
const myCar = new Car('Tesla');
console.log(myCar.model); // ์ถ๋ ฅ: Tesla
3. ์ด๋ฒคํธ ํธ๋ค๋ฌ์์์ this ํ์ฉ
const button = document.getElementById('myButton');
button.addEventListener('click', function() {
this.disabled = true;
console.log('Button clicked!');
});
์ฐ๊ด๋ ๊ธฐ์
Arrow Function
Arrow Function์ ์์ฒด์ ์ธ this
๋ฅผ ๊ฐ์ง์ง ์๊ณ , ์ฃผ๋ณ ์ค์ฝํ์ this
๋ฅผ ์์๋ฐ์ต๋๋ค. ์ด๋ก ์ธํด ํจ์๊ฐ ์ด๋์์ ์ ์๋์๋์ง์ ๋ฐ๋ผ this
๊ฐ ๊ฒฐ์ ๋๋ฏ๋ก ์ฃผ์๊ฐ ํ์ํฉ๋๋ค. Arrow Function์ ๋ฉ์๋๋ก ์ฌ์ฉํ ๋๋ณด๋ค ์ผ๋ฐ์ ์ธ ํจ์๋ก ์ฌ์ฉ๋ ๋ ๋ ์ ์ ํฉ๋๋ค.
const myFunction = () => {
console.log(this); // ์์ ์ค์ฝํ์ this๋ฅผ ์ฐธ์กฐ
};
this
์ ์ดํด๋ ์๋ฐ์คํฌ๋ฆฝํธ์์ ํต์ฌ์ ์ธ ๋ถ๋ถ ์ค ํ๋์ด๋ฉฐ, ์ ์ ํ ํ์ฉ์ ์ฝ๋์ ๊ฐ๋
์ฑ๊ณผ ์ ์ง๋ณด์์ฑ์ ํฐ ์ํฅ์ ๋ฏธ์นฉ๋๋ค.
'IT' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
BFF(Backend For Frontend) ๊ฐ๋ ๋ฐ ํ์ฉ (0) | 2024.03.01 |
---|---|
์๋ฐ์คํฌ๋ฆฝํธ Prototype: ๊ฐ๋ , ํ์ฉ, ์ฅ๋จ์ , ์์ ์ฝ๋ (0) | 2024.02.28 |
SSL/TLS: ์ํธํ์ ๋ณด์์ ์ํ ํต์ฌ ํ๋กํ ์ฝ (0) | 2024.02.27 |
์ปดํจํฐ ๊ณผํ(CS)์ ํต์ฌ ์ดํด: ๊ธฐ์ด๋ถํฐ ์ฌํ๊น์ง (0) | 2024.02.27 |
LMS(Learning Management System): ํ์ต์ ํจ์จ์ ์ผ๋ก ๊ด๋ฆฌํ๋ ์์คํ (0) | 2024.02.27 |
๋๊ธ