1. 클래스
ES6에서는 자바나 파이썬 같은 객체지향 언어에서 쓰이는 클래스가 도입되었다.
class Developer {
constructor(name){
this.name = name;
}
hello(){
return 'Hello World! I am ' + this.name + ' and I am a web developer';
}
}
- class : 새로운 객체를 생성할 때 쓰이는 식별자 앞에 쓰인다.
- constructor : 객체를 초기화할 때 쓰이는 메서드이다.
클래스 상속
class ReactDeveloper extends Developer {
installReact(){
return 'installing React .. Done.';
}
}
var nathan = new ReactDeveloper('Nathan');
nathan.hello(); // Hello World! I am Nathan and I am a web developer
nathan.installReact(); // installing React .. Done.
- extends를 사용해서 자식 클래스를 만들 수 있는데, 자식 클래스는 부모 클래스에 정의된 메서드를 오버라이드할 수 있다.
- 오버라이드는 부모 클래스에 정의된 메서드를 자식 클래스에서 새롭게 정의하고 교체한다는 의미이다.
- React에서는 React 컴포넌트 클래스를 상속받았기 때문에 render(), JSX, this.state 등의 다양한 메서드를 사용할 수 있는 것이다.
2. let과 const로 변수 선언하기
- 기존의 var 키워드 : 변수를 전역에 선언하기 때문에, 문제를 발생시켰다. ES6에서는 이를 해결하기 위해 let과 const를 도입하였다.
- const로 선언한 변수는 선언 이후에 값을 바꿀 수 없고,
- let으로 선언한 변수는 바꿀 수 있다.
- 이 둘은 1) 모두 변수 선언 시 사용되며, 2) 지역변수이기 때문에 함수 밖에서 호출할 수 없다.
const name = "David";
let age = 28;
var occupation = "Software Engineer";
- React에서는 변수가 필요한 모든 곳에 쓰이기 때문에, 반드시 알아둬야 한다.
3. 화살표 함수
- 화살표 함수를 쓰면 함수를 좀 더 짧은 문법으로 작성할 수 있다.
// regular function
const testFunction = function() {
// content..
}
// arrow function
const testFunction = () => {
// content..
}
- 매개변수가 하나라면 괄호를 생략할 수 있다.
const testFunction = (firstName, lastName) => {
return firstName+' '+lastName;
}
const singleParam = firstName => {
return firstName;
}
4. 구조 분해 할당
- 객체나 배열 일부를 쉽게 변수로 해체할 수 있다.
const developer = {
firstName: 'Nathan',
lastName: 'Sebhastian',
developer: true,
age: 25,
}
//destructure developer object
const { firstName, lastName } = developer;
console.log(firstName); // returns 'Nathan'
console.log(lastName); // returns 'Sebhastian'
console.log(developer); // returns the object
- developer 객체의 firstName과 lastName을 해체하여, 새로운 변수인 firstName과 lastName에 할당하였다.
- 만약, firstName을 새로운 변수인 name에 할당하고 싶다면? 다음과 같이 하면 된다.
const { firstName:name } = developer;
console.log(name); // returns 'Nathan'
React에서는?
- 메서드 안에서 state를 해체할당하는 데 자주 쓰인다.
reactFunction = () => {
const { name, email } = this.state;
};
5. 맵과 필터
const users = [
{ name: 'Nathan', age: 25 },
{ name: 'Jack', age: 30 },
{ name: 'Joe', age: 28 },
];
- map : map 안의 조건대로 배열의 모든 값에 적용한다.
- filter : filter 안의 조건이 참인 값에만 적용된다.
<ul>
{users
.filter(user => user.age > 26)
.map(user => <li>{user.name}</li>)
}
</ul>
6. 템플릿 리터럴
- 내장된 표현식을 허용하는 문자열 리터럴이다.
var a = 5;
var b = 10;
console.log("Fifteen is " + (a + b) + " and\nnot " + (2 * a + b) + ".");
기존 이렇게 표현했던 방식과 다르게, 더욱 읽기 쉽도록 다음과 같이 표현할 수 있게 되었다.
var a = 5;
var b = 10;
console.log(`Fifteen is ${a + b} and not ${2 * a + b}.`);
자료 출처
React를 배우기 전에 알아야 할 JavaScript기초
React 학습 전 알아야 할 ES6 문법 정리
medium.com
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Template_literals
Template literals
템플릿 리터럴은 내장된 표현식을 허용하는 문자열 리터럴입니다. 여러 줄로 이뤄진 문자열과 문자 보간기능을 사용할 수 있습니다. 이전 버전의 ES2015사양 명세에서는 "template strings" (템플릿 문
developer.mozilla.org
과제 및 풀이
Q1.
- Cat 클래스는 name 멤버변수를 가진다. 생성자에서 name 멤버변수를 초기화한다.
- Cat 클래스는 hello() 메소드를 가진다. hello 메서드는 "Mew~ I'm [name]" 을 콘솔에 출력한다. 출력하는 문자열은 템플릿 리터럴을 사용하여 작성한다.
- myCat 이라는 Cat 인스턴스를 생성하고 hello() 메소드를 실행하시오.
- 인스턴스를 생성함과 동시에 name 멤버변수를 임의의 문자열로 초기화한다.
class Cat { // Cat 클래스 생성
constructor(name) { // name 멤버변수
this.name = name; // 생성자에서 name 멤버변수 초기화
}
hello() { //hello() 메소드 생성
console.log(`Mew~ I'm ${this.name}`); //템플릿 리터럴을 사용하여 문자열 출력
}
}
const myCat = new Cat("hoo"); //myCat이라는 Cat 인스턴스 생성
myCat.hello();
Q2. 위에서 만든 Cat 클래스를 상속받아 CheeseCat 자식클래스를 작성하시오.
- CheeseCat 클래스는 grooming 메소드를 가진다. grooming 메소드에서는 "grooming..." 이라는 문자열을 콘솔창에 출력한다.
- CheeseCat 클래스 Cat 클래스의 hello() 메소드를 오버라이딩한다. hello() 메소드에서는 "Cheese~ I'm [name]" 을 콘솔에 출력한다. 출력하는 문자열은 템플릿 리터럴로 작성한다.
class CheeseCat extends Cat { //extends를 통해 Cat 클래스를 상속받은 CheeseCat 자식 클래스 생성
hello() {
console.log(`Cheese~ I'm ${this.name}`); //Cat 클래스의 hello() 메소드 오버라이딩
}
grooming() { //grooming() 메소드
console.log("grooming...");
}
}
const myCheeseCat = new CheeseCat("loo");
myCheeseCat.hello();
myCheeseCat.grooming();
Q3-1. 아래의 함수 선언문(sum1)을 함수 표현식으로 바꾸시오. (sum2)
Q3-2. 만든 함수 표현식의 익명함수를 arrow function으로 바꾸시오.(implicit return 하시오) (sum3)
function sum1(x, y) {
return x + y;
}
let sum2 = function (x, y) { //function 사용하여 함수표현식으로 변경
return x + y;
let sum3 = (x, y) => x + y; //화살표 함수를 사용하여 함수표현식으로 변경
Q4-1. users 객체 배열을 생성하고 map을 사용하여 출력하시오. filter를 사용해서 나이가 28 이상인 사람만 출력하시오.
Q4-2. 출력 형태: "[name], [age]"
Q4-3. map을 사용하여 배열의 인덱스도 함께 출력하시오. 출력 형태: "[index]. [name], [age]"
const users = [
{ name: 'Alice', age: 18 },
{ name: 'Bob', age: 30 },
{ name: 'Carol', age: 22 },
{ name: 'Dave', age: 28 }
];
users.map( user => console.log(`${user.name}, ${user.age}`)); //map을 사용하여 출력
users.filter(user => user.age >= 28).map(user => console.log(`${user.name}, ${user.age}`)); //filter를 사용하여 나이가 28세 이상인 사람만 출력
users.map((data, index) => console.log(`${index}. ${data.name}, ${data.age}`)); //배열의 index를 함께 출력
Q5-1. 배열 해체 할당
let a, b, rest;
[a, b] = [10, 20];
console.log(a); // 실행 결과 : 10
console.log(b); // 실행 결과 : 20
[a, b, ...rest] = [10, 20, 30, 40, 50];
console.log(rest); //실행 결과 : [ 30, 40, 50 ]
Q5-2. 객체 해체 할당
let {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40}
console.log(a); // 실행 결과 : 10
console.log(b); // 실행 결과 : 20
console.log(rest); // 실행 결과 : { c: 30, d: 40 }
'Group Study (2020-2021) > React' 카테고리의 다른 글
[React] 4주차 스터디 - 배열 데이터 렌더링 및 관리 (0) | 2020.11.29 |
---|---|
[React] 3주차 스터디(2) - input 상태 관리하기 (0) | 2020.11.01 |
[React] 3주차 스터디 - LifeCycle API (0) | 2020.10.27 |
[React] 2주차 스터디 - props와 state (0) | 2020.10.25 |