์ ์ธ๋ฐฉ์
๐ ์ผ๋ฐ ํจ์ ์ ์ธ ๋ฐฉ์
function square(x) { return x * x; }
๐ ํ์ดํ ํจ์ ์ ์ธ ๋ฐฉ์
const square = (x) => { return x * x; };
this ๋ฐ์ธ๋ฉ
์ผ๋ฐ ํจ์๋ this๊ฐ ๋์ ์ผ๋ก ๋ฐ์ธ๋ฉ๋๋ ๋ฐ๋ฉด ํ์ดํ ํจ์๋ ๋ฐ๋ก ์์ ์ค์ฝํ์ this์ ๊ฐ๋ค.
๐ ์ผ๋ฐํจ์
const cat = { name: 'meow', foo1: function() { const foo2 = function() { console.log(this.name); } foo2(); } }; cat.foo1(); // undefined
- cat.foo1() ๋ฉ์๋ ํธ์ถ ์ ๋ด๋ถ ํจ์ foo2๊ฐ ์คํ๋จ
- ํจ์๊ฐ ํธ์ถ๋์ผ๋ฏ๋ก foo2 ๋ด๋ถ์ this๋ ์ง์ ๋์ง ์์์ ๊ณง ์ ์ญ ๊ฐ์ฒด๋ฅผ ๊ฐ๋ฆฌํด
- ์ ์ญ ๊ฐ์ฒด์ name์ด๋ ์์ฑ์ ์กด์ฌํ์ง ์์ผ๋ฏ๋ก undefined๊ฐ ๋ธ
๐ ํ์ดํ ํจ์
const cat = { name: 'meow', foo1: function() { const foo2 = () => { console.log(this.name); } foo2(); } }; cat.foo1(); // meow
ํ์ดํ ํจ์์์์ this๋ ์๊ธฐ๊ฐ ์ ์๋ ์ค์ฝํ์ ์กด์ฌํ๋ this๋ฅผ ๊ฐ๋ฅดํจ๋ค. ์ฆ ์๊ธฐ์ ์์์ ์๋ ์ค์ฝํ์ this๋ฅผ ๊ฐ๋ฅดํค๋ ๊ฒ์ด๋ค. ๋ฐ๋ผ์ ๋ด๋ถํจ์์ ์ด๋ ํ ๋ฐ์ธ๋ฉ๋ ํ์ง ์์์ง๋ง ํ์ดํ ํจ์๋ก ํจ์๋ฅผ ์ ์ํ๊ธฐ ๋๋ฌธ์ this๊ฐ cat ๊ฐ๋ฅดํค๊ฒ ๋๋ค.
์์ฑ์ ํจ์๋ก ์ฌ์ฉ
ํ์ดํํจ์๋ ํ๋กํ ํ์
ํ๋กํผํฐ๋ฅผ ๊ฐ์ง๊ณ ์์ง ์๊ธฐ ๋๋ฌธ์ ์์ฑ์ ํจ์๋ก ์ฌ์ฉ์ด ์ด๋ ต๋ค.
์ฌ๊ธฐ์ ์์ฑ์ ํจ์๋ new ํค์๋๋ฅผ ์ฌ์ฉํ์ฌ ๊ฐ์ฒด์ ์์ฑ๊ณผ ๋ฉ์๋๋ฅผ ์ ์ํ๋ฉฐ ํด๋น ๊ฐ์ฒด๋ฅผ ์์ฑํ๋ ๋ฐ ์ฌ์ฉ๋๋ค.
์ฌ๊ธฐ์ ์์ฑ์ ํจ์๋ new ํค์๋๋ฅผ ์ฌ์ฉํ์ฌ ๊ฐ์ฒด์ ์์ฑ๊ณผ ๋ฉ์๋๋ฅผ ์ ์ํ๋ฉฐ ํด๋น ๊ฐ์ฒด๋ฅผ ์์ฑํ๋ ๋ฐ ์ฌ์ฉ๋๋ค.
// ์ผ๋ฐํจ์ ์์ฑ์ ํจ์ ์ ์ function Person(name, age) { this.name = name; this.age = age; } // ๊ฐ์ฒด ์์ฑ var person1 = new Person('John', 30); var person2 = new Person('Alice', 25); console.log(person1.name); // ์ถ๋ ฅ: John console.log(person2.age); // ์ถ๋ ฅ: 25
arguments ์ ๋ฌ
์ผ๋ฐํจ์์์๋ ํจ์ ๋ด์์ ๋ชจ๋ ์ ๋ฌ๋ ์ธ์๋ฅผ ํฌํจํ๊ณ ์๋ arguments๋ณ์๊ฐ ์ ๋ฌ๋์ด ์ฌ์ฉํ ์ ์์ง๋ง, ํ์ดํ ํจ์์์๋ arguments๋ณ์๊ฐ ์ ๋ฌ๋์ง ์๋๋ค.
๐ ์ผ๋ฐ ํจ์
function regularFunction() { console.log(arguments); } regularFunction(1, 2, 3); // ์ถ๋ ฅ: { '0': 1, '1': 2, '2': 3 }
๐ ํ์ดํ ํจ์
const arrowFunction = () => { console.log(arguments); } arrowFunction(1, 2, 3); // Error: arguments is not defined
ํ์ดํ ํจ์์์๋ arguments๋ฅผ ์ฌ์ฉํ ์ ์๊ธฐ ๋๋ฌธ์ ์์ ๊ฐ์ ์ฝ๋๋ ์๋ฌ๋ฅผ ๋ฐ์์ํจ๋ค. ๋์ ์ ํ์ดํ ํจ์์์๋ Rest parameters๋ฅผ ์ฌ์ฉํ์ฌ ๋ชจ๋ ์ ๋ฌ๋ ์ธ์๋ฅผ ๋ฐ๊ณ , args ๋ฐฐ์ด์ ์ ์ฅํ ํ ์ถ๋ ฅํ ์ ์๋ค.
const arrowFunctionWithRest = (...args) => { console.log(args); } arrowFunctionWithRest(1, 2, 3); // ์ถ๋ ฅ: [1, 2, 3]