화살표 함수란, ES6에 새롭게 나온 함수의 새로운 형태입니다.
function test() { // 함수 선언 - 생각만 하고 있는 상태
// 코드의 집합
}
test(); // 함수 호출 - 코드를 실행
const test = function() { // 함수 선언 - 생각만 하고 있는 상태
// 코드의 집합
}
test(); // 함수 호출 - 코드를 실행
const test = () => {//함수 선언 - 생각만 하고 있는 상태
//코드의 집합
}
test(); // 함수 호출 -코드를 실행
[=>]
라는 화살표 기호를 사용했다고 하여 화살표 함수라고 부릅니다!화살표 함수는 표현식의 개수, 매개변수의 유무에 따라 문법이 조금씩 다릅니다.
함수명 = () => 표현식;
{}
를 생략할 수 있습니다.hello = () => alert('hello world');
hello();
함수명 = () => {
표현식1;
표션식2;
}
{}
에 묶어서 처리해야 합니다.hello2 = () => {
const a = 10;
const b = 20;
console.log(a + b);
};
hello2();
함수명 = (매개변수) => {표현식;};
함수명 = 매개변수 => {표현식;};
()
안에 담지 않아도 됩니다.()
를 쓴다고 해서 오류가 나지는 않습니다.
#1. return을 사용 할때는 {}를 사용!
square = x => {
return x *x;
};
#2. return을 사용하지 않고 싶다면 {} 생략 가능!
square = x => x*x;
console.log(square(5);
함수명 = (매개변수1, 매개변수2) => {표현식};
()
안에 작성해야 합니다.square = (x,y) => {
return x *y;
};
console.log(square(4,6));
const x = this;
console.log(x);
window
객체입니다.const myFunction = () => {
return this;
};
console.log(myFunction);
window
객체입니다.const person = {
firstName : '길동',
lastName : '홍',
id : 1022,
fullName : function() {
return this.lastName + " " + this.firstName;
}
};
console.log(person.fullName);
아래와 같이 fullName : function()이 아니라
메서드 내부에서 사용한 this는 메서드를 소유한 해당 객체를 의미합니다.
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>ES6 테스트</title>
<script>
</script>
</head>
<body>
<button onclick="this.style.display='none'">
클릭하면 제거!
</button>
</body>
</html>
this
는 이벤트 받는 객체를 의미합니다.<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>ES6 테스트</title>
</head>
<body>
<button id="btn">클릭</button>
<h3 id="demo"></h3>
<script>
hello = function() {
document.getElementById("demo").innerHTML += this;
}
// The window object calls the function:
window.addEventListener("load", hello);
// A button object calls the function:
document.getElementById("btn").addEventListener("click", hello);
</script>
</body>
</html>
window
인 것을 확인할 수 있습니다.HTMLButton
요소인 것을 확인할 수 있습니다.<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>ES6 테스트</title>
</head>
<body>
<button id="btn">클릭</button>
<h3 id="demo"></h3>
<script>
hello = () => {
document.getElementById("demo").innerHTML += this;
}
// The window object calls the function:
window.addEventListener("load", hello);
// A button object calls the function:
document.getElementById("btn").addEventListener("click", hello);
</script>
</body>
</html>
window
, 클릭이벤트와 사용되었어도 window
로 처리되는 것을 확인할 수 있습니다.함수의 매개변수를 호출하지 않아도 기본값으로 처리되도록 설정하는 문법이 추가 되었습니다.
function 함수명(매개변수명 = 기본값, 매개변수명 = 기본값,...){
}
function test(x,y=10) {
return x + y;
}
console.log(test(5)); // x 값만 저장
console.log(test(5,20)); // x와 y값 모두 저지정
첫번째 결과에 두번째 매개변수 값을 호출하지 않아도 기본값으로 계산 된 것을 볼 수 있습니다.