JavaScript⑨

정혜지·2022년 8월 9일

자바스크립트

class

클래스는 class 키워드를 사용하여 정의
클래스 이름은 생성자 함수와 마찬가지로 파스칼 케이스를 사용하는 것이 일반적이다.

클래스 특징

  • 무명의 리터러러로 생성가능(런타임에 생성가능)
  • 변수나 자료구조(객체, 배열 등)에 저장 가능
  • 함수의 매개변수에게 전달 가능
  • 함수의 반환값으로 사용 가능

따지고 보면 클래스도 함수~!

constructor

생성자 : 객체 생성시, 프로퍼티 초기화

extends

생성자 함수

function Animal () {
      this.name = name;
      this.speed = speed;

      run = function (speed) {
        console.log(`${this.speed}로 run() 실행`)
      }
      stop = function (name) {
        console.log(`${this.name}이 멈춤 stop()`)
      }
    }

클래스 형태로 변경

 class Animal {

      // 생성자 : 객체 생성시, 프로퍼티 초기화
       constructor(name) {
        this.name = name;
        this.speed = 0;
       }

      // 메소드
      run (speed) {
        console.log(`${this.speed}로 run() 실행`)
      }
      stop (name) {
        console.log(`${this.name}이 멈춤 stop()`)
      }

    }
   // extends 
    class Cat extends Animal {  //Animal의 모든속성을 Cat이 상속받음
      sleep() {
        console.log('12시간 이상 잠')
      };
    };

    const cat = new Cat('navi');
    console.log(cat);
    cat.sleep();
    cat.run();
    cat.stop();

콜백함수

비동기를 통해서 결과 출력

function fetchData (studentId) {
    let student;
    setTimeout(function() {
      student = {
      id: studentId
      }
    }, 0);

    return student;
  }

  const student1 = fetchData(1)
  console.log(student1)		--> undefined

예상결과 {id: 1}
실제결과 undefined


문제발생원인

  • student 객체가 만들어지는 로직이 비동기로 처리됨
  • student 객체가 만들어지는 동안 return student가 실행
  • 따라서, 생성되지 않은 객체를 갖고있는 student가 출력
  • undefined가 출력됨

문제해결? ---> 콜백함수


콜백함수로 변경

  function fetchData (studentId, callback) {
    let student;
    setTimeout(function() {
      student = {
      id: studentId
      }
      callback (student)
    }, 0);

    return student;
  }

  fetchData(1, function (student) {
    console.log(student)
  })

콜백함수의 문제점 -> 콜백지옥
---> promise



Storage

웹 스토리지
web storage

스토리지 객체

종류
local/session

로컬 : 브라우저 한정
세션 : 서버

구조
key : value

메소드 & 프로퍼티

  • setItem(key, value) : 데이터를 스토리지에 저장

  • getItem(k) : 저장된 데이터를 반환

  • removeItem(k) : 저장된 데이터를 삭제

  • key(index) : 해당 인텍스에 저장된 키 반환

-length : 저장된 항목의 개수 반환

profile
오히려 좋아

0개의 댓글