ES5에서 static 메서드를 선언하기 본문

2021 프론트 엔드 로드맵 따라가기/JS

ES5에서 static 메서드를 선언하기

알 수 없는 사용자 2021. 6. 6. 18:44

ES6 에서는 해당 클래스 내부에 static키워드를 이용해 static 메서드를 선언할 수 있었는데 ES5에서 똑같이 구현하려니 방법이 바로 떠오르지 않아 검색해보았다.

 

생성자 함수에 점 표기법을 이용하여 메서드를 바로 선언하면 된다.

 

아래는 모두 Store의 static 메서드들이다.

// Store
function Store() {}

Store.getBooks = function () {
  let books;

  if (localStorage.getItem("books") === null) {
    books = [];
  } else {
    books = JSON.parse(localStorage.getItem("books"));
  }

  return books;
};

Store.displayBooks = function () {
  const books = Store.getBooks();

  // instanciate UI
  const ui = new UI();

  books.forEach((book) => {
    ui.addBookToList(book);
  });
}

Store.addBook = function (book) {
  const books = Store.getBooks();

  books.push(book);

  localStorage.setItem("books", JSON.stringify(books));
}

'2021 프론트 엔드 로드맵 따라가기 > JS' 카테고리의 다른 글

AJAX란  (0) 2021.06.07
비동기(Asynchronous) 프로그래밍이란  (0) 2021.06.06
ES6 class Inheritance  (0) 2021.06.05
ES6 class  (0) 2021.06.05
[중요] Prototypal inheritance  (0) 2021.06.05
Comments