[JavaScript] 기본 문법 정리

Woongbin·2023년 3월 15일
0

웹 프로그래밍

목록 보기
1/8

구조 분해 할당 (Destructuring)

구조 분해 할당은 배열이나 객체의 속성을 해제하여 그 값을 각각의 변수에 담을 수 있게 해준다.

const player = {
   name: 'Gwon seowon',
   club : 'amorra',
   address : {
     city : 'busan'
  }
}

위의 객체에서 city값을 불러 올려면 위와 같이 작성 해야 한다.

console.log(player.address.city)

하지만 여기서 구조 분해 할당을 사용하면 아래와 같은 코드가 된다.

const { name, club, address : {city} } = player
console.log(name, club, city) // destructuring
console.log(`${name} lives in ${city}!`) // template literal

위 코드의 결과 값은 다음과 같다.


API 통신

fetch

fetch는 API를 불러 올 때 사용하는 함수이다.

fetch('json 파일 주소')
 .then((response) => response.json())
 .then((data) => console.log(data));

위 코드는 json 파일을 불러와서 콘솔에 출력하는 코드이다.

promise

promise는 비동기 처리에 사용되는 객체이다.

function getData() {
  return new Promise(function(resolve, reject) {
    $.get('url 주소/products/1', function(response) {
      if (response) {
        resolve(response);
      }
      reject(new Error("Request is failed"));
    });
  });
}

getData().then(function(data) {
  console.log(data); // response 값 출력
}).catch(function(err) {
  console.error(err); // Error 출력
});

위 코드는 서버에서 제대로 응답 받으면 response 값을 출력하고 아니면 error 값을 콘솔에 출력하는 코드이다.

async / await

async/await도 promise와 마찬가지로 비동기 처리하는 문법이다.

async function logName() {
  var user = await fetchUser('domain.com/users/1');
  if (user.id === 1) {
    console.log(user.name);
  }
}

위 코드는 서버에서 사용자를 불러와 사용자의 아이디가 1이면 사용자의 이름을 콘솔에 출력하는 코드이다.


클래스 (Class)

이번에는 클래스를 사용해 볼 것이다.
import와 export를 이용하면 클래스를 모듈화 시킬 수 있다.

export class Animal {
  constructor(type, legs) {
    this.type = type;
    this.legs = legs;
  }
  makeNoise(sound = "Loud Noise") {
    console.log(sound);
  }
  get metaData() {
    return `Type: ${this.type}, Legs: ${this.legs}`;
  }
  static return10() {
    return 10;
  }
}

export class Cat extends Animal {
  makeNoise(sound = "meow") {
    console.log(sound);
  }
}

위 코드는 클래스를 생성하고 Cat이라는 클래스에 Animal이라는 클래스를 상속하는 코드이다. 이제 아래 코드는 방금 만든 클래스를 사용하는 코드이다.

import { Animal, Cat } from "./Animal";

const animal = new Animal();
console.log(animal.makeNoise());
const cat = new Cat();
console.log(cat.makeNoise());

위 코드의 결과 값은 다음과 같다.


ES6 문법

화살표 함수

화살표 함수는 일반함수 보다 간편하게 사용할 수 있다.

let sum = (a, b) => a + b;

위 코드는 화살표 함수의 간단한 예제로 a + b의 값을 계산하는 함수이다.

익명 함수

익명 함수는 말 그대로 함수 이름 없이 선언할 수 있다.
익명 함수는 function을 사용하는 방법과 화살표 함수를 사용하는 방법이 있다. ( 화살표 함수는 위에서 했으므로 생략 )

const hello = function(){
    console.log("Hello World!");
};

위 코드는 Hello()를 했을 때 Hello World!가 출력되는 코드이다.

0개의 댓글