티스토리 뷰

 

화살표 함수(() => {})는 함수를 간단하게 표현할 수 있는 ES6문법입니다. 일반 javascript(function ())과 비슷한 방식으로 동작하지만 몇가지 분명한 차이점이 있습니다.

문법(Syntax)

// (param1, param2, paramN) => expression
// ES5 
var add = function(x, y) { 
	return x+y; 
}
// ES6 
let add = (x, y) => {return x+y};

위의 예제에서 보시다시피, 표현법이 다르죠? Regular function(ES5)와 Arrow function(ES6)는 결과는 같은데 타이핑이 절반 가까이 줄어들었습니다. 보기에도 깔끔하구요

또한, 괄호를 생략할 수 있는 경우가 있어서 더 줄어들 수 있죠.

  • input값인 인자(argument)가 한개라면 ()괄호를 생략 가능

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

  • {}안에 들어갈 표현식이 하나일 경우, 한줄로 써버릴 수도 있습니다.

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

  • 인자(argument)가 없는 경우? _만 쓰는 것 가능

let sayHi = _ => console.log("Hi");

this

일반 함수의 this

자바스크립트의 경우 함수 호출 방식에 의해 this에 바인딩할 어떤 객체가 동적으로 결정됩니다. 다시 말해, 함수를 선언할 때 this에 바인딩할 객체가 정적으로 결정되는 것이 아니고 함수를 호출할 때(런타임 시) 함수가 어떻게 호출되었는지에 따라 this에 바인딩할 객체가 동적으로 결정됩니다.

  • 생성자 함수와 객체 메소드: this = 객체
  • (생성자 함수와 객체 메소드를 제외한) 내부함수, 콜백 함수 등: this = 전역객체(window)
function Prefixer(prefix) { this.prefix = prefix; } Prefixer.prototype.prefixArray = function (arr) { 
	// (A) return arr.map(function(x) => { 
    	return this.prefix + ' ' + x; // (B) 
    });
};
var pre = new Prefixer('Hi'); 
console.log(pre.prefixArray(['Lee', 'Kim']));

콜백 함수 내부의 this 메소드를 호출한 객체(생성자 함수의 인스턴스)를 가리키게 하려면 아래의 세가지 방법이 있다.

  1. 참조변수 이용하기: that = this;
function Prefixer(prefix) { this.prefix = prefix; } Prefixer.prototype.prefixArray = function(arr) { 
	var that = this; // this: Prefixer 생성자 함수의 인스턴스 return arr.map(function(x) => { 
    	return that.prefix + ' ' + x; 
      });
    };
var pre = new Prefixer('Hi'); 
console.log(pre.prefixArray(['Lee', 'Kim']));
  1. map(func, this)
function Prefixer(prefix) { this.prefix = prefix; } Prefixer.prototype.prefixArray = function (arr) { 
		return arr.map(function (x) {
        		return this.prefix + ' ' + x;
                }, this); // this: Prefixer 생성자 함수의 인스턴스 
              };
var pre = new Prefixer('Hi');
console.log(pre.prefixArray(['Lee', 'Kim']));

​
  1. bind(this)
// Solution 3: bind(this) function Prefixer(prefix) {
		this.prefix = prefix; 
} Prefixer.prototype.prefixArray = function (arr) { 
		return arr.map(function (x) { 
        		return this.prefix + ' ' + x; 
     }.bind(this)); // this: Prefixer 생성자 함수의 인스턴스 }; 
var pre = new Prefixer('Hi'); 
console.log(pre.prefixArray(['Lee', 'Kim']));

 

화살표 함수를 사용해서는 안되는 경우

화살표 함수는 Lexical this를 지원하므로 콜백 함수로 사용하기 편리하다. 하지만 화살표 함수를 사용하는 것이 오히려 혼란을 불러오는 경우도 있으므로 주의하여야 한다.

#4.1 메소드

화살표 함수로 메소드를 정의하는 것은 피해야 한다. 화살표 함수로 메소드를 정의하여 보자.

 Bad const person = { name: 'Lee', sayHi: () => console.log(`Hi ${this.name}`) }; person.sayHi(); // Hi undefined

위 예제의 경우, 메소드로 정의한 화살표 함수 내부의 this는 메소드를 소유한 객체, 즉 메소드를 호출한 객체를 가리키지 않고 상위 컨택스트인 전역 객체 window를 가리킨다. 따라서 화살표 함수로 메소드를 정의하는 것은 바람직하지 않다.

이와 같은 경우는 메소드를 위한 단축 표기법인 ES6의 축약 메소드 표현을 사용하는 것이 좋다.

const person = { name: 'Lee', sayHi() { // === sayHi: function() { 
		console.log(`Hi ${this.name}`); 
        }
}; person.sayHi(); // Hi Lee

#4.2 prototype

화살표 함수로 정의된 메소드를 prototype에 할당하는 경우도 동일한 문제가 발생한다. 화살표 함수로 정의된 메소드를 prototype에 할당하여 보자.

const person = { name: 'Lee', }; Object.prototype.sayHi = () => console.log(`Hi ${this.name}`); 
person.sayHi(); // 

Hi undefined

화살표 함수로 객체의 메소드를 정의하였을 때와 같은 문제가 발생한다. 따라서 prototype에 메소드를 할당하는 경우, 일반 함수를 할당한다.

// Good const person = { name: 'Lee', }; Object.prototype.sayHi = function() { 
	console.log(`Hi ${this.name}`); 
}; person.sayHi(); // Hi Lee

#4.3 생성자 함수

화살표 함수는 생성자 함수로 사용할 수 없다. 생성자 함수는 prototype 프로퍼티를 가지며 prototype 프로퍼티가 가리키는 프로토타입 객체의 constructor를 사용한다. 하지만 화살표 함수는 prototype 프로퍼티를 가지고 있지 않다.

// false 
const Foo = () => {}; // 화살표 함수는 prototype 프로퍼티가 없다 console.log(Foo.hasOwnProperty('prototype'));

const foo = new Foo(); // TypeError: Foo is not a constructor

#4.4 addEventListener 함수의 콜백 함수

addEventListener 함수의 콜백 함수를 화살표 함수로 정의하면 this가 상위 컨택스트인 전역 객체 window를 가리킨다.

// Good var button = document.getElementById('myButton');
button.addEventListener('click', function() {
	console.log(this === button); // => true this.innerHTML = 'Clicked button'; 
    });​

따라서 addEventListener 함수의 콜백 함수 내에서 this를 사용하는 경우, function 키워드로 정의한 일반 함수를 사용하여야 한다. 일반 함수로 정의된 addEventListener 함수의 콜백 함수 내부의 this는 이벤트 리스너에 바인딩된 요소(currentTarget)를 가리킨다.

// Bad var button = document.getElementById('myButton');
button.addEventListener('click', () => {
	console.log(this === window); // => true this.innerHTML = 'Clicked button'; 
});

'Java Script & j Query > Java Script' 카테고리의 다른 글

클로저  (0) 2021.06.07
생성자 함수  (0) 2021.06.03
Prototype(프로토 타입)  (0) 2021.06.01
[Java Script]-클로저란?  (0) 2021.03.31
[JavaScript]Form Data란?  (0) 2020.09.27