[TIL] JS: ES6

송나은·2021년 1월 25일
0

JavaScript

목록 보기
3/23

변수

var / let / const

  • ES6에서는 var 키워드는 사용하지 않는다.
  • 기본적으로 const를 사용하고 재할당이 필요한 경우 let을 사용한다.
  • let 키워드 사용 시 스코프는 최대한 좁게 만든다.

Template Literals

일반적인 문자열과 달리 여러 줄에 걸쳐 문자열을 작성할 수 있고, 공백이 있는 그대로 적용된다.

${...}

연산자를 사용하지 않아도 새로운 문자열을 삽입할 수 있다. 내부의 표현식은 문자열 타입으로 변환된다.

ex) ${1+1}의 경우 문자'2'로 변환된다.

Arrow Function

1. 기본 문법

// 매개변수 지정 방법
    () => { ... } // 매개변수가 없을 경우
     x => { ... } // 매개변수가 한 개인 경우, 소괄호를 생략할 수 있다.
(x, y) => { ... } // 매개변수가 여러 개인 경우, 소괄호를 생략할 수 없다.

// 함수 몸체 지정 방법
x => { return x * x }  // single line block
x => x * x             // 함수 몸체가 한줄의 구문이라면 중괄호를 생략할 수 있으며 암묵적으로 return된다. 위 표현과 동일하다.

() => { return { a: 1 }; }
() => ({ a: 1 })  // 위 표현과 동일하다. 객체 반환시 소괄호를 사용한다.

() => {           // multi line block.
  const x = 10;
  return x * x;
};

2. 호출

const pow = x => x * x;
console.log(pow(10)); // 100

// callback
const arr = [1, 2, 3];
const pow = arr.map(x => x * x);

console.log(pow); // [ 1, 4, 9 ]

Parameter 매개변수

1. Rest parameter

parameter 앞에 세개의 점 ... 을 붙여서(=Spread 문법을 사용하여) 정의한 parameter.

function bar(param1, param2, ...rest) {
  console.log(param1); // 1
  console.log(param2); // 2
  console.log(rest);   // [ 3, 4, 5 ]
}

bar(1, 2, 3, 4, 5);
  • .length()에 영향을 주지 않는다.
function foo(...rest) {}
console.log(foo.length); // 0

function bar(x, ...rest) {}
console.log(bar.length); // 1

function baz(x, y, ...rest) {}
console.log(baz.length); // 2
  • 가변 인자의 목록을 배열로 전달받을 수 있다.
function sum(...args) {
  console.log(arguments); // Arguments(5) [1, 2, 3, 4, 5, callee: (...), Symbol(Symbol.iterator): ƒ]
  console.log(Array.isArray(args)); // true
  return args.reduce((pre, cur) => pre + cur);
}
console.log(sum(1, 2, 3, 4, 5)); // 15

2. Spread 문법

대상을 개별 요소로 분리하는 문법이다.
console.log(...[1, 2, 3]) // 1, 2, 3

  • 함수의 인수로 사용하는 방법
function foo(v, w, x, y, z) {
  console.log(v); // 1
  console.log(w); // 2
  console.log(x); // 3
  console.log(y); // 4
  console.log(z); // 5
}

// ...[2, 3]는 [2, 3]을 개별 요소로 분리한다(→ 2, 3)
// spread 문법에 의해 분리된 배열의 요소는 개별적인 인자로서 각각의 매개변수에 전달된다.
foo(1, ...[2, 3], 4, ...[5]);
  • 배열에서 사용하는 방법

    Contact 생략이 가능하다!

const arr = [1, 2, 3];
console.log([...arr, 4, 5, 6]); // [ 1, 2, 3, 4, 5, 6 ]
  • push, splice, copy
// 기존 배열에 다른 배열의 개별 요소를 각각 push 하는 방법
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

arr1.push(...arr2); // == arr1.push(4, 5, 6);
console.log(arr1); // [ 1, 2, 3, 4, 5, 6 ]

// splice (삽입)
const arr1 = [1, 2, 3, 6];
const arr2 = [4, 5];

arr1.splice(3, 0, ...arr2); // == arr1.splice(3, 0, 4, 5);
console.log(arr1); // [ 1, 2, 3, 4, 5, 6 ]

// copy
const arr = [1, 2, 3];
const copy = [...arr];

console.log(copy); // [ 1, 2, 3 ]
copy.push(4); // copy를 변경한다.
console.log(copy); // [ 1, 2, 3, 4 ]

// arr은 변경되지 않는다.
console.log(arr);  // [ 1, 2, 3 ]

3. Rest/Spread Property

Object.assign을 대체하여 객체를 병합/변경할 수 있다.

// 객체의 병합
const merged = { ...{ x: 1, y: 2 }, ...{ y: 10, z: 3 } };
console.log(merged); // { x: 1, y: 10, z: 3 }

// 특정 프로퍼티 변경
const changed = { ...{ x: 1, y: 2 }, y: 100 };
// changed = { ...{ x: 1, y: 2 }, ...{ y: 100 } }
console.log(changed); // { x: 1, y: 100 }

// 프로퍼티 추가
const added = { ...{ x: 1, y: 2 }, z: 0 };
// added = { ...{ x: 1, y: 2 }, ...{ z: 0 } }
console.log(added); // { x: 1, y: 2, z: 0 }

Object property

1. 축약

property 값을 변수로 사용하는 경우 이름을 생략할 수 있다.

let x = 1, y = 2;
const obj = { x, y };

console.log(obj); // { x: 1, y: 2 }

method 선언 시, function 키워드를 생략할 수 있다.

const obj = {
  name: 'Song',
  // 메소드 축약 표현
  sayHi() {
    console.log('Hi! ' + this.name);
  }
};

obj.sayHi(); // Hi! Song

Object.create() 함수를 사용하지 않고 객체 내부에서 설정할 수 있다.

const parent = {
  name: 'parent',
  sayHi() {
    console.log('Hi! ' + this.name);
  }
};

const child = {
  // child 객체의 프로토타입 객체에 parent 객체를 바인딩하여 상속을 구현한다.
  __proto__: parent,
  name: 'child'
};

parent.sayHi(); // Hi! parent
child.sayHi();  // Hi! child

2. Destructuring

객체의 각 프로퍼티를 객체로부터 추출하여 변수 리스트에 할당한다. 이때 할당 기준은 property key 이다.

const obj = { firstName: 'Ungmo', lastName: 'Lee' };

// property key를 기준으로 destructuring할당이 이루어진다. 순서는 의미가 없다.
// 변수 lastName, firstName가 선언되고 obj가 Destructuring되어 할당된다.
const { lastName, firstName } = obj;

console.log(firstName, lastName); // Ungmo Lee

Class

1. 정의

  • 인스턴스 생성: new 연산자와 함께 클래스 이름(=Constructor)을 호출한다.
  • Constructor 생성자

    class 내에 Constructor가 2개 이상 존재하면 문법 에러가 발생한다.

// 클래스 선언문
class Person {
  // constructor(생성자)
  constructor(name) {
    // this 클래스가 생성할 인스턴스
    this._name = name; // _name 클래스 필드의 선언과 초기화
  }

  sayHi() {
    console.log(`Hi! ${this._name}`);
  }
}
// 인스턴스 생성
const me = new Person('Lee');
me.sayHi(); // Hi! Lee

console.log(me) // Person {_name: "Lee"}

2. 클래스 필드

클래스 필드의 선언과 초기화는 반드시 constructor 내부에서 실시한다.

3. Getter, Setter

클래스 필드에 값을 할당할 때마다 클래스 필드의 값을 조작할 때 사용한다. 접근자 프로퍼티.

  • Get 키워드
    무언가를 취득할 때 사용하므로 반드시 무언가를 반환 해야한다.
class Foo {
  constructor(arr = []) {
    this._arr = arr;
  }

  // getter: get 키워드 뒤에 오는 메소드 이름 firstElem은 클래스 필드 이름처럼 사용된다.
  get firstElem() {
    // getter는 반드시 무언가를 반환해야 한다.
    return this._arr.length ? this._arr[0] : null;
  }
}

const foo = new Foo([1, 2]);
// 필드 firstElem에 접근하면 getter가 호출된다.
console.log(foo.firstElem); // 1
  • Set 키워드
    값을 할당하는 형식으로 사용한다.
class Foo {
  constructor(arr = []) {
    this._arr = arr;
  }
  
// setter: set 키워드 뒤에 오는 메소드 이름 firstElem은 클래스 필드 이름처럼 사용된다.
  set firstElem(elem) {
    // ...this._arr은 this._arr를 개별 요소로 분리한다
    this._arr = [elem, ...this._arr];
  }
}
// 클래스 필드 firstElem에 값을 할당하면 setter가 호출된다.
foo.firstElem = 100;

console.log(foo.firstElem); // 100

4. Static method

애플리케이션 전역에서 사용할 유틸리티 함수를 생성할 때 주로 사용한다.

  • 정적 메소드는 클래스이름으로 호출한다.
  • 정적 메소드는 인스턴스로 호출할 수 없다. (= this를 사용할 수 없다.)

5. 클래스 상속

상위 클래스가 가지고 있는 메소드를 하위 클래스가 재정의하여 사용하는 방식이다. (= overriding)

  • Extends 키워드
    부모 클래스 Circle을 상속받는 자식 클래스 Cylinder를 정의한다.
  • Super 키워드
    부모 클래스를 참조하거나 부모 클래스의 constructor를 호출할 때 사용한다.
lass Parent {}

class Child extends Parent {
  // ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor
  constructor() {}
}

const child = new Child();
profile
그때그때 공부한 내용과 생각을 기록하는 블로그입니다.

0개의 댓글