Arrow function
1. νμ΄ν ν¨μ?
μλ° μ€ν¬λ¦½νΈ ES6μμ μΆκ°λμμΌλ©°, κ°κ²°νκ² ν¨μλ₯Ό ννν μ μλ€.
νμ΄ν ν¨μ
const ArrowFunc = () => {
return "νμ΄ν ν¨μ";
}
μΌλ° ν¨μ
function NormalFunc(){
return "μΌλ° ν¨μ";
}
2. μΌλ° ν¨μμ νμ΄ν ν¨μ μ°¨μ΄μ
2 - 1 . this
μΌλ° ν¨μμμμ thisλ μ μκ°μ²΄ (window)λ₯Ό κ°λ₯΄ν¨λ€.
function Example(){
console.log(this);
};
Example()
// console.logμ μ°ν thisλ μλμ° κ°μ²΄λ₯Ό νμνλ€.
νμ΄ν ν¨μμμμ thisλ μΈμ λ μμ μ€μ½νμ thisλ₯Ό κ°λ¦¬ν¨λ€.
function arrFun() {
this.name = "νμ΄";
return {
name: "λ°μ΄";
speak: () => {
console.log(this.name);
},
};
}
μμ μ½λμ κ°μ΄ arrFunμ λ°νκ°μ²΄μμ speakλ νμ΄ν ν¨μλ₯Ό μ΄μ©νμ¬ name : "λ°μ΄"μ console.log(this.name)μ λ°ννκ³ μλ€.
νμ§λ§ νμ΄ν ν¨μμ thisλ μμ μ€μ½νμΈ arrFunμ thisλ₯Ό κ°λ¦¬ν€λ―λ‘, "νμ΄"λ₯Ό μΆλ ₯νκ² λλ€.
2 - 2 . μμ±μ ν¨μ
μμ±μ ν¨μλ₯Ό μ¬μ©ν μ μλ μΌλ° ν¨μμ λ¬λ¦¬, νμ΄ν ν¨μλ μ¬μ©μ΄ λΆκ°νλ€. (prototype νλ‘νΌν°λ₯Ό κ°μ§κ³ μμ§ μκΈ° λλ¬Έ)
function fun() {
this.name = "μΌλ°ν¨μ";
}
const arrFun = () => {
this.name = "νμ΄νν¨μ";
};
const funA = new fun();
console.log(funA.name); // μΌλ°ν¨μ
const funB = new arrFun(); // Error
2 - 3 . argument
μΌλ° ν¨μλ μ€νμ΄ λ λ argument λ³μκ° μ λ¬μ΄ λκΈ° λλ¬Έμ μ¬μ©μ΄ κ°λ₯νμ§λ§ νμ΄ν ν¨μλ argumentκ° μ λ¬λμ§ μμ μ¬μ©μ΄ λΆκ°νλ€.
function fun() {
console.log(arguments); // Arguments(3) [[1, 2, 3, ... ]]
}
fun(1, 2, 3);
const arrFun = () => {
console.log(arguments); // Uncaught ReferenceError: arguments is not defined
};
arrFun(1, 2, 3);
reference
λͺ¨λ μλ°μ€ν¬λ¦½νΈ
Last updated