ES6 버전 문법에 대해 알아보자.
참고자료 출처: replit / 설명 아래 기재
이름 없는 함수
//ES5
function() {}
//ES6
() => {}
이름 있는 함수
//ES5
function getName() {}
//ES6
const getName = () => {}
호출
getName()
인자를 받을 때
//ES5
const getName = function(name) {}
//ES6
const getName = (name) => {}
const getName = name => {}
인자가 하나일 때는 소괄호 생략이 가능하다.
인자가 두개일 때는 생략할 수 없다.
//ES5
const getName = function(name,age){}
//ES6
const getName = (name,age) => {}
return 함수
//ES5
function hi(text) {
text += '하세요';
return text;
}
//ES6
const hi = text => {
text += '하세요';
return text
};
만약 함수의 실행내용이 딱히 없어 return만 한다면 return 키워드와 중괄호가 생략가능하다.
//ES5
function getName(name) {
return name;
}
//ES6
const hi = name => { return name };
const hi = name => name;
const obj = {
name : 'Lee',
sayName : () => { console.log(`hi + ${this.name}`);}
};
obj1.sayName();
이렇게 써주면 객체의 this를 바인딩하지 않고 전역 객체가 바인딩된다.
대신
const obj = {
name: 'Lee',
sayHi : function(){
console.log(`hi ${this.name}`);
}
};
obj.sayHi();
let button = document.getElementById('myButton');
button.addEventListener('click', () => {
console.log(this === window); // => true
this.innerHTML = 'Clicked button';
});
let button = document.getElementById('myButton');
button.addEventListener('click', function() {
console.log(this === button); // => true
this.innerHTML = 'Clicked button';
});
참고자료 출처 : https://jeong-pro.tistory.com/110
string을 작성할 때 back tick
으로도 string을 감쌀 수 있다.
back tick
으로 감싸면 그 안에 변수를 넣어서 표현할 수 도 있다.
const name = '김개발';
cosnt hi = `안녕하세요. 저는 ${name}입니다.`;
변수를 사용하려면 ${}
으로 변수를 감싸줘한다.
< 예제 >
function sayHello(name,age){
return `Hello ${name} you are ${age} years old`;
}
const greetSunju = sayHello("Sunju",20)
console.log(greetSunju)
참고자료 출처: 유튜브 '노마드 코더'
( https://www.youtube.com/watch?v=mLTUtMARkqc&list=PLLUCyU7SBaR7tOMe-ySJ5Uu1UlEBznxTr&index=15 )
예를들어,
let detail = '자세히
보아야
이쁘다';
console.log(detail);
는 오류이다.
template literal에서는 string을 입력한대로 개행이 된다.
let detail = `자세히
보아야
이쁘다
내코드..`;
console.log(detail);
string을 찾기 위해서는 그동안 indexOf
를 사용하였다.
이제는 startsWith
, endsWith
, includes
3가지 method가 생겼다.
const email = 'yealee.kim87@gmail.com';
console.log(email.startsWith('ye')); //true
console.log(email.endsWith('com')); //true
console.log(email.includes('@gmail')); //true
특정 문자열을 반복하고 싶으면
'#'.repeat(3);