javascript- 화살표 함수

현우.·2024년 6월 22일

JavaScript

목록 보기
30/31
post-thumbnail

화살표 함수

함수 표현식에 대한 간결한 대안으로 ES6에서 나온 함수 표현식이다.

화살표 함수의 특징

문법 간결

function 키워드( function() {} ) 대신 화살표(⇒) 사용하기 때문이 문법이 간결하고 가시성이 좋다.

생성자 함수로 사용할 수 없다.

화살표함수는 prototype 이 없기 때문에 함수를 new연산자와 호출하더라도 prototype이 없어 자신의 인스턴스 객체를 만들 수 없다.

코드 📄

const student3= {
    name: 'kar',
    study: () =>{
        console.log('공부하는중..');
    }
}
const obj3 = new student3.study(); 
// TypeError: student3.study is not a constructor

코드 📄

const Student= () =>console.log('공부해라');

console.log(Student.hasOwnProperty('prototype')); // false
const study =new Student(); // Student is not a constructor

cf) ES6부터 사용가능한 메소드의 축약방식 또한 생성자함수 사용이 불가능하다.

코드 📄

const student3= {
    name: 'kar',
    study(){
        console.log('공부하는중..');
    }
}
const obj3 = new student3.study(); 
// TypeError: student3.study is not a constructor

그러나 ES6이전의 메소드 선언방식은 생성자 함수로 사용이 가능하기 때문에 주의해야한다.

코드 📄

const student3= {
    name: 'kar',
    study: function(){
        console.log('공부하는중..');
    }
}
const obj3 = new student3.study();  // 공부하는중...

arguments 객체를 가지지 않는다.

화살표함수는 arguments 유사배열 객체를 프로퍼티로 가지지 않는다.

코드 📄

const func = () => console.log(arguments);
func(1,2,3,4);
// ReferenceError: arguments is not defined


해결

Rest 파라미터를 이용하여 배열형태로 인자들을 받을 수 있다.

코드 📄

const func = (...args) => console.log(args);
func(1,2,3,4); // [ 1, 2, 3, 4 ]

this에 대한 바인딩이 정적으로 결정된다.

즉 화살표 함수를 정의할 때 this가 결정된다.

화살표 함수의 this는 함수밖의 제일 근접한 상위 스코프의 this를 가리킨다.

    function Prefixer(prefix) {
        this.prefix = prefix;
    }
    
    Prefixer.prototype.prefixArray = function (arr) {
       return arr.map(x => `${this.prefix}  ${x}`);
    };
    
    const pre = new Prefixer('Hi');
    console.log(pre.prefixArray(['Lee', 'Kim']));
    // [ 'Hi  Lee', 'Hi  Kim' ]
  • this는 상위 스코프인 prefixArray 메소드 내의 this를 가리킨다.
profile
학습 기록.

0개의 댓글