ํ์ดํ ํจ์๋ ES6๋ฌธ๋ฒ์ ๋๋ค. function ํค์๋ ์ฌ์ฉํด์ ํจ์๋ฅผ ๋ง๋ ๊ฒ๋ณด๋ค ๊ฐ๋จํ ํจ์๋ฅผ ํํํ ์ ์์ต๋๋ค. ํ์ดํ ํจ์๋ ํญ์ ์ต๋ช ์ ๋๋ค.
// ์ผ๋ฐ ํจ์
var foo = function () { console.log("foo") }; // foo
// ํ์ดํ ํจ์
var bar = () => console.log("bar"); // bar
1. ํ์ดํ ํจ์์ ๊ธฐ๋ณธ๋ฌธ๋ฒ
// ๋งค๊ฐ๋ณ์๊ฐ ์๋ ๊ฒฝ์ฐ
var foo = () => console.log('bar');
foo(); // bar
// ๋งค๊ฐ๋ณ์๊ฐ ํ๋์ธ ๊ฒฝ์ฐ
var foo = x => x;
foo('bar'); // bar
// ๋งค๊ฐ๋ณ์๊ฐ ์ฌ๋ ค๊ฐ์ธ ๊ฒฝ์ฐ
var foo = (a, b) => a + b; // ๊ฐ๋จํ๊ฒ ํ์ค๋ก ํํํ ๋ "{}" ์์ด ๊ฐ์ด ๋ฐํ๋ฉ๋๋ค.
foo(1, 2); // 3
var foo = (a, b) => { return a + b };
foo(1, 2); // 3
var foo = (a, b) => { a + b }; // "{}"๋ฅผ ์ฌ์ฉํ๋๋ฐ return์ด ์์ ๋
foo(1, 2); // undefined
var foo = (a, b) => { // ์ฌ๋ฌ์ค ์ผ์ ๋
var c = 3;
return a + b + c;
}
foo(1, 2, 3) // 6
/*
"{}"๋ฅผ ์ฌ์ฉํ๋ฉด ๊ฐ์ ๋ฐํํ ๋ return์ ์ฌ์ฉํด์ผํฉ๋๋ค.
"{}"๋ฅผ ์ฌ์ฉํ์ง ์์ผ๋ฉด undefied๋ฅผ ๋ฐํํฉ๋๋ค.
"{}"์ ์ฌ์ฉํ ๋๋ ์ฌ๋ฌ์ค์ ์ผ์ ๋ ์ฌ์ฉํฉ๋๋ค.
*/
// ๊ฐ์ฒด๋ฅผ ๋ฐํํ ๋
var foo = () => ( { a: 1, b: 2, c: 3 } );
foo(); // { a: 1, b: 2, c: 3 };
์ฝ๋ฐฑ ํจ์์์๋ ์ฌ์ฉํ ์ ์์ต๋๋ค.
// ES5
var numbers = [1, 4, 9];
var oddArr = numbers.filter(function (x) { return x % 2 !== 0;});
console.log(oddArr); // [1, 9]
// ES6
var numbers = [1, 4, 9];
var oddArr = numbers.filter( x => (x % 2) !== 0 );
console.log(oddArr); // [1, 9]
2. ํ์ดํ ํจ์ this
์ผ๋ฐ ํจ์์ ํ์ดํ ํจ์์ ์ฐจ์ด์ ์ด ์์ต๋๋ค. ์ผ๋ฐํจ์๊ฐ ์ ์ญ ์ปจํ ์คํธ์์ ์คํ๋ ๋ this๊ฐ ์ ์ํฉ๋๋ค. ํ์ดํํจ์๋ this๋ฅผ ์ ์ํ์ง ์์ต๋๋ค.
ํจ์์ ๋ด๋ถํจ์, ์ฝ๋ฐฑํจ์์ ์ฌ์ฉ๋๋ this๋ window์ ๋๋ค.
let cat = {
sound: "meow",
soundPlay: function () {
console.log(this) // ๊ฐ.
setTimeout(function () {
console.log(this) // ๋.
console.log(this.sound); // ๋ค.
}, 1000);
}
}
cat.soundPlay();
// ๊ฐ. cat {sound: "meow", soundPlay: ƒ}
// ๋. window
// ๋ค. undefined -----> undefined์ธ ์ด์ ๋ window์ sound๊ฐ ์์ด์์
๋๋ค.
์ผ๋ฐํจ์์์์ ์ ์ ํ this๋ฅผ ์ ๋ฌํ๋ ๋ฐฉ๋ฒ์ด ์์ต๋๋ค.
// ํจ์์์ that ๋ณ์๋ฅผ ์ ์ธํ๊ธฐ
let cat = {
sound: "meow",
soundPlay: function () {
let that = this // that ์ฌ์ฉ
setTimeout(function () {
console.log(that.sound);
}, 1000);
}
}
cat.soundPlay();
// 1์ด ํ์ ... "meow"
// bind ์ฌ์ฉํ๊ธฐ
let cat = {
sound: "meow",
soundPlay: function () {
setTimeout(function () {
console.log(this.sound);
}.bind(this), 1000); // bind ์ฌ์ฉ
}
}
cat.soundPlay();
// 1์ด ํ์ ... "meow"
ํ์ดํ ํจ์๋ฅผ ์ฌ์ฉํด๋ณด๊ฒ ์ต๋๋ค.
let cat = {
sound: "meow",
soundPlay: function () {
setTimeout(() => {
console.log(this.sound);
}, 1000);
}
}
cat.soundPlay();
// 1์ด ํ์ ... "meow"
์ด๊ฒ ๊ฐ๋ฅํ ์ด์ ๋ ํด๋ก์ ํจ์์ฒ๋ผ ๋ฐ๊นฅ์ ํจ์์ ์ ๊ทผํด์ this๋ฅผ ์ฌ์ฉํฉ๋๋ค.
'Frontend๐ฑ > JavaScript' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ณ์] var, let, const์ ์ฐจ์ด (0) | 2023.05.24 |
---|---|
var, let, const์ ์ฐจ์ด โค ๋ณ์ ์ ์ธ ๋ฐ ํ ๋น, ํธ์ด์คํ , ์ค์ฝํ (0) | 2023.04.03 |
์๋ฐ์คํฌ๋ฆฝํธ ํจ์ ์ ์ธ๊ณผ ํธ์ถ (0) | 2023.04.03 |