PDH 개발 공부

Arrow Functions 본문

JavaScript/ES6

Arrow Functions

IFBB 2021. 7. 9. 16:53

화살표 함수

  • 화살표 함수는 짧은 문자로 함수를 표현이 가능하다

기본 함수

기존(Basic)

// 기존(Basic)

let add = function(x,y){
return x + 6;
};

console.log(add(10,20)); // 30

축약(ES6)

//

let add = (x, y) => x + y;

console.log(add(10, 20)); // 30;

console.log(add instanceof Function); // true

// 즉 Arrow Functions 도 function 이다

여러 매개 변수가 있는 함수

(p1, p2, ..., pn) => expression;

=> expression
// 다음 표현식

=> { return expression; }
// 다음 표현식과 동일함

기존(Basic)

let numbers = [4,2,6];
numbers.sort(function(a,b){ 
    return b - a; 
});
console.log(numbers); // [6,4,2]

축약(Basic)

let numbers = [4,2,6];
numbers.sort((a,b) => b - a);
console.log(numbers); // [6,4,2]

단일 매개 변수가 있는 함수

(p1) => { statements }

p => { statements }
// 다음 표현식

let names = ['John', 'Mac', 'Peter'];
let lengths = names.map(name => name.length);

console.log(lengths); / [ 4, 3, 5 ]


매개변수가 없는 JavaScript Arrow 함수

() => { statements }

// 예시
let logDoc = () => console.log(window.document);
logDoc();

  • 화살표 함수에 매개 변수가 없다면 다음과 같이 괄호를 사용 해야한다.하지만 중괄호를 생략 가능

매개변수 정의와 Arrow 사이의 줄 바꿈

let multiply = (x,y) 
=> x * y; 

let multiply = (x,y) => 
x * y;

let multiply = (
  x,
  y
) => 
x * y;
  • javaScript를 사용하면 다음 예와 같이 매개변수 사이에 줄 바꿈을 사용할 수 있다.

Arrow 함수 본문의 명령문 및 표현식

10 + 20;


if (x === y) {
    console.log('x equals y');
}


let square = x => x * x; //화살표 함수의 본문에 표현식을 사용하는 경우 중괄호를 사용할 필요가 없다




let except = msg => {  // 그러나 명령문을 사용하는 경우 다음 예와 같이 중괄호를 쌍으로 묶어야함
    throw msg;
};

JavaScript Arrow 함수 및 객체 리터럴

let setColor = function (color) {
    return {value: color}
};

let backgroundColor = setColor('Red');
console.log(backgroundColor.value); // "Red"
  • 정상적으로 반환이 된다 다음과 같이 Arrow 함수를 반환 한다면

p => {object:literal}

let setColor = color => {value: color };
  • 에러가 발생한다 이유는 javascript엔진은 블록과 객체를 구별 할 수 없기 때문이다. 이 문제를 해결 하기 위해선

let setColor = color => ({value: color });
  • 개체 리터럴을 괄호로 묶으면 해결이 된다

Arrow function vs regular function

(this 장에서 한번 다뤘던 내용!)

[this](this창 가기!)

  • 이 둘 사이에는 주요 차이점이 있다.
  1. Arrow 함수에서 this,arguments , super , new , tartget 는 어휘이다. 이는 arrow 함수가 둘러싸는 어휘 범위에서 변수를 사용한다는 것을 의미한다.

  2. arrow 함수는 함수 생성자로는 사용 할 수 없다. 사용하는 경우 new arrow기능에서 새로운 객체를 생성하는 키워드에서 오류가 발생한다.


function Car() {
    this.speed = 0;

    this.speedUp = function (speed) {
        this.speed = speed;
        setTimeout(function () {
            console.log(this.speed); // undefined
        }, 1000);

    };
}

let car = new Car();
car.speedUp(50);
  • JavaScript에서는 새 함수는 자체 this 값을 정의 한다. 하지만 arrow 함수 같은 경우에는 다르다.

Arrow function vs regular function 보안 1


function Car() {
    this.speed = 0;

    this.speedUp = function (speed) {
        this.speed = speed;
        let self = this;
        setTimeout(function () {
            console.log(self.speed);
        }, 1000);

    };
}

let car = new Car();
car.speedUp(50); // 50;
  • self 를 주어서 function 내의 값을 찾아 낸다

Arrow function vs regular function 보안 2


function Car() {
    this.speed = 0;

    this.speedUp = function (speed) {
        this.speed = speed;
        setTimeout(
            () => console.log(this.speed),
            1000);

    };
}

let car = new Car();
car.speedUp(50); // 50;
  • arrow function 을 사용해서 해결

JavaScript arrow 함수 및 arguments 객체

function show() {
    return x => x + arguments[0];
}

let display = show(10, 20);
let result = display(5);
console.log(result); // 15
  • 화살표 함수에서는 arguments 개체가 없다.
  • 그러나 arguments 객체는 show() 화살표 함수가 아닌 함수에 속한다
  • arrow 함수에서는 new.target 키워드가 없다.

JavaScript arrow 함수 및 프로토타입 속성

regular 함수

function dump( message ) {
    console.log(message);
}
console.log(dump.hasOwnProperty('prototype')); // true

arrow 함수

let dump = message => console.log(message);
console.log(dump.hasOwnProperty('prototype')); // false

결론 : # arrow 함수의 구문이 더 명확 하기 때문에 콜백 , 클로저에 arrow 함수를 사용하는 것이 좋다

요약

  • (...args) => expression;화살표 함수를 정의하는 데 사용
  • (...args) => { statements }여러 문이 있는 화살표 함수를 정의하는 데 사용 .
  • 화살표 함수에는 this또는 super 에 대한 바인딩이 없다 .
  • 화살표 함수에는 arguments개체, new.target키워드 및 prototype속성이 없다

'JavaScript > ES6' 카테고리의 다른 글

Basic VS ES6  (0) 2021.07.03
let 키워드에 대해서  (0) 2021.06.29
Comments