ํ์ดํํจ์
๊ธฐ์กด์ function ํํ๋ฐฉ์๋ณด๋ค ๊ฐ๊ฒฐํ๊ฒ ํจ์๋ฅผ ํํํ ์ ์๋ค. ํ์ดํํจ์๋ ํญ์ ์ต๋ช ์ด๋ฉฐ, ์์ ์ this, arguments, super, new.target์ ๋ฐ์ธ๋ฉํ์ง ์๋๋ค. ๋ฐ๋ผ์ ์์ฑ์๋ก๋ ์ฌ์ฉํ ์ ์๋ค.
- ํ์ดํํจ์ ๋์ ์ํฅ : ์งง์ ํจ์, ์์ ์ค์ฝํ this
์งง์ ํจ์
var materials = ["Hydrogen", "Helium", "Lithium", "Beryllium"];
materials.map(function (material) {
return material.length;
}); // [8, 6, 7, 9]
materials.map((material) => {
return material.length;
}); // [8, 6, 7, 9]
materials.map(({ length }) => length); // [8, 6, 7, 9]์์์ค์ฝํ this
function Person() {
this.age = 0;
setInterval(() => {
this.age++; // |this|๋ person ๊ฐ์ฒด๋ฅผ ์ฐธ์กฐ
}, 1000);
}
var p = new Person();์ผ๋ฐ ํจ์์์ this๋ ์ ์ญ๊ฐ์ฒด๋ฅผ this๋ก ์ ์ํ๋ค. ํ์ง๋ง ํ์ดํ ํจ์ this๋ ์์ ์ค์ฝํ์ this์ ๋์ผํ ๊ฐ์ ๊ฐ๋๋ค. ๋ฐ๋ผ์ ์ ์์ ์์ setInterval๋ก ์ ๋ฌ๋ this๋ Person์ this๋ฅผ ๊ฐ๋ฆฌํค๋ฉฐ, Person ๊ฐ์ฒด์ age์ ์ ๊ทผํ๋ค.
ํ์ดํํจ์๋ฅผ ์ฌ์ฉํ๋ฉด ์๋๋ ์๊ฐ
๋ฉ์๋
const cat = {
name: 'meow';
callName: () => console.log(this.name);
}
cat.callName(); // undefined์ด ๊ฒฝ์ฐ ํ์ดํํจ์์ ์์ ์ค์ฝํ๋ ์ ์ญ this๊ฐ ๋๋ค. ๋ฐ๋ผ์ ๋ฉ์๋๋ก ํ์ดํํจ์๋ฅผ ์ฌ์ฉํ๋ฉด ์๋๋ค.
๋ฉ์๋์ ๊ฒฝ์ฐ, ํธ์ถํ ๊ฐ์ฒด์ this๋ก ๋ฐ์ธ๋ฉ๋๋ ์ผ๋ฐ ํจ์๋ฅผ ์ฌ์ฉํ์
์์ฑ์
const Foo = () => {};
const foo = new Foo(); // TypeError: Foo is not a constructorํ์ดํํจ์์๋ prototype์ด ์๊ธฐ์ ์์ฑ์๋ก ์ฌ์ฉํ ์๋ ์๋ค.
addEventListener()์ ์ฝ๋ฐฑํจ์
const button = document.getElementById("myButton");
button.addEventListener("click", () => {
console.log(this); // Window
this.innerHTML = "clicked";
});
button.addEventListener("click", function () {
console.log(this); // button ์๋ฆฌ๋จผํธ
this.innerHTML = "clicked";
});addEventListener์ ์ฝ๋ฐฑํจ์์์ this ๋ ์ด๋ฒคํธ๋ฆฌ์ค๋๊ฐ ํธ์ถ๋ ์๋ฆฌ๋จผํธ๋ก ๋ฐ์ธ๋ฉ๋๋ค.
ํ์ง๋ง ํ์ดํํจ์๋ฅผ ์ฌ์ฉํ ๊ฒฝ์ฐ ์์์ค์ฝํ๋ก ๋ฐ์ธ๋ฉ๋๋ฏ๋ก, ์ ์ญ this๊ฐ ์ฌ์ฉ๋๊ฒ ๋๋ค.
์ถ์ฒ
https://github.com/JaeYeopHan/Interview_Question_for_Beginner/tree/master/JavaScript#promise