화살표 함수(Arrow Function)

p-q·2021년 9월 28일
1

JavaScript

목록 보기
4/11

기존의 함수 정의방식

var ㅁ = function () {
 // ...
};

화살표 함수를 이용한 함수 정의

var a = () => {
 //...
};

1.단순한 자바스크립트 표현식

() => 10+20; // {} 필요없음

2.함수 선언 방식

() => {
	print();
    let();
    return 10+20;
};

3.전달 인자(parameter)가 하나인 경우

const a = num => {
	return num * 10;
};

const b = num => num*10;
a(10); // 100
b(10); // 100

this 바인딩의 변화

화살표 함수에서 사용되는 this 바인딩은 기존함수 this와 다른 방식을 가지고있다
화살표 함수의 this는 함수를 선언할 때의 상위 스코프의 this로 바인딩 될 객체가 정해진다.

const foo = {
	name: "bar",
    age: 10,
    printThis() {
    	console.log(this); // {name: "bar", age: 10, printThis: f}
        const innerFunc = () => {
        	return this; // {name: "bar", age: 10, printThis: f}
        };
    }
    console.log(inerFunc());
   	}
};

foo.printThis();

innerFunc의 상위 스코프는 printThis이기 때문에 printThis의 내부 this와 innerFunc의 내부 this는 같은 값으로 바인딩 된다.

setTimeout에서의 this

일반 함수에서 setTimeout에서의 this는 window를 가르키지만
화살표 함수에서는 상위 스코프의 this로 값이 바인딩 된다.

const foo = {
	name: "bar",
    age: 10,
    getThisarrowFunc function() {
   		console.log(this); // {name: "bar", age:10, getThisarrowFunc: f}
        setTimeout(() => {
        	console.log(this); // {name: "bar", age:10, getThisarrowFunc: f}
        }, 1000);        
    },
    getThisFunc: function() {
    	console.log(this); // {name: "bar", age:10, getThisFunc: f}
        setTimeout(function() {
        	console.log(this) // window
        }, 1000)
    }
};

foo.getThisArrowFunc();
foo.getThisFunc();

그러나 엄격모드('use strict') 일때는 바인딩 되지 않는다.

"use strict"  // 엄격모드
(function() {
	setTimeout(() => {
    	console.log(this); // undefined 이 경우는 this 가 바인딩 되지 않는다
    }, 1000);	
})();

addEventListener에서의 this

addEventListener의 두 번째 인자로 화살표 함수를 넣으면 this는 상위 스코프의 this를 가르킨다.

const button = document.getElementById("this-button");
button.innerText = "함수 호출 버튼";

button.addEventListener("click", () => {
	console.log(this === window); // true
    console.log(this.innerText); // undefined
});

addEventListener 함수에서 this 를 사용하는 경우

화살표 함수가 아닌 일반 함수를 사용해준다.
일반 함수로 정의된 addEventListener 함수의 this 는 currentTarget 을 가리킨다.

const button = document.getElementById("this-button");
button.innerText = "함수 호출 버튼";

button.addEventListener("click", function() {
	console.log(this === button); // true
    console.log(this.innerText); // 함수 호출 버튼
});

addEventListener 콜백 함수 안에서 사용되는 this

는 class로 생성된 개체 인스턴스를 가리킨다

class Foo {
	constructor() {
    	this.name = "bar";
    }
    register() {
    	window.addEventListener("keydown", e => this.shomMethod(e));
    }
    someMethod(event) {
    	console.log(this.name); // bar
        console.log(event.keyCode); // Enter 입력시 63
    }
}

const baz = new Foo();
baz.register();

call,bind,apply로 바인딩 변경 불가

일반 함수의 this와 다르게 화살표 함수에서의 this는 call,bind,apply 메소드로 this 에 바인딩된 값을 변경할 수 없다.

this.foo = "bar";
const normalFunc = function() {
	return this.foo;
};
const arrowFunc = () => this.foo;

console.log(normalFunc.cll({ foo: "baz" }) // baz
console.log(arrowFunc.cll({ foo: "baz" }) // bar 화살표 함수는 this값 변경 불가

생성자 함수로 사용 불가

const Foo = () => {};
const foo = new Foo(); // Uncaught TypeError: Foo is not a constructor

화살표함수의 사용 용도와 this의 변화의대해 주의하며 학습할것

출처 : [https://joshua1988.github.io/vue-camp/]

profile
ppppqqqq

0개의 댓글