본문 바로가기
기초/프론트엔드 종합반 HTML&CSS, JS, React

5주차_ HTML/CSS/JS로 만드는 스타벅스 웹사이트2

by Hyeon_E 2023. 1. 13.

JS 화살표 함수

( ) => { }    vs    function ( ) { }

활살표 함수를 사용할때 {}에 식을 넣으면 반환이 안됨. {}을 쓸려면 retrun을 사용

축약형으로 객체데이터를 반환할때는 꼭 ()소괄호로 감싸주어야 함

const double = function (x) {
  return x * 2;
};
console.log("double:", double(7));	//14

const doubleArrow = (x) => {
  return x * 2;
};
console.log("doubleArrow:", doubleArrow(7));	//14

const doubled = x => x * 2;
console.log("doubled:", doubled(7));	//14

const myName = (x) => ({ name: "H.E" });
console.log("myName:", myName());	//myName: {name: 'H.E'}

JS IIFE(Immediately-Invoked Function Expreesion)

즉시 실행함수. 익명함수를 만들자마자 바로 실행 시킬 수 있음

const a = 7;
function double2() {
  console.log(a * 2);	//14
}
double2();

(function () {
  console.log(a * 2);	//14
})();

(function () {
  console.log(a * 2);	//14
}());

JS 호이스팅(Hoisting)

함수 선언부가 유효범위 최상단으로 끌어올려지는 현상

double3();

// const double3 = function () { 오류가 남
//   console.log("double3:", a * 2);
// };

function double3() {
  console.log("double3:", a * 2);
}

JS 타이머 함수

  • setTimeout(함수, 시간): 일정 시간 후 함수 실행
  • setInterval(함수, 시간): 시간 간격마다 함수 실행
  • clearTimeout(함수, 시간): 설정된 Timeout 함수를 종료
  • clearInterval(함수, 시간): 설정된 Interval 함수를 종료
const timer = setTimeout(() => {
  console.log("3초뒤 log발생");
}, 3000); //3초 뒤
const h1El = document.querySelector("h1");
h1El.addEventListener("click", () => {
  clearTimeout(timer);
});

const timer2 = setInterval(() => {
  console.log("3초마다 log발생");
}, 3000); //3초 뒤
const h1El2 = document.querySelector("h2");
h1El2.addEventListener("click", () => {
  clearInterval(timer2);
});

JS 콜백(Callback)

함수의 인수로 사용되는 함수

function timeout() {
  setTimeout(() => {
    console.log("Hi!");
  }, 3000);
}
timeout();
console.log("Done!");	//Done이 log로 나온 후 Hi!가 log로 나옴

function timeout2(cb) {
  setTimeout(() => {
    console.log("Hi!");
    cb();
  }, 3000);
}
timeout2(() => {
  console.log("Done!");	//Hi! 후 Done! log 나옴
});

JS 생성자 함수(prototype)

생성자 함수는 일반 함수. 유사한 객체를 여러 개 만들 때 유용하게 사용

  • 함수 이름의 첫 글자는 대문자로 시작
  • 반드시 'new'연산자를 붙여 실행
function User(first, last) {
  //함수이름을 파스칼 케이스로 적는 것은 그 함수가 new라는 키워드와 함께 생성자로써 사용된다는 것을 이름만으로 알수 있게함
  this.firstName = first;
  this.lastName = last;
}
User.prototype.getFullName = function () {
  return `${this.firstName} ${this.lastName}`;
};
//user라는 함수에 숨어져 있는 prototype이라는 속성부분에다가 getFullName을 할당해주면
//새롭게 몇개에 객체가 만들어져도 이 부분의 함수는 메모리에 한번만 만들어짐. 객체가 사용할때는 이 부분을 참조하는 것

const he = new user("SH", "L"); //new 키워드를 사용해 생성자 함수. 하나의 객체 데이터가 생성됨
const amy = new user("Amy", "Clarke");
const neo = new user("Neo", "Smith");
//{}, "", [] 등 특정한 기호를 가지고 데이터를 만드는 것을 리터럴 방식이라 함
//new라는 키워드를 통해서 생성자 함수로 실행한 결과를 반환해서 할당된 변수를 생성자 함수의 인스턴스라고 부름
//줄여서 인스턴스라고 부르는 것 위에 he, amy, neo가 인스턴스

JS this

  • 일반(Normal) 함수는 호출 위치에 따라 this 정의
  • 화살표(Arrow) 함수는 자신이 선언된 함수 범위에서 this 정의
const he = {
  name: "H.E",
  normal: function () {
    //he라는 객체 내부에서 실행이 되어 호출위치(he.normal)에 he가 this가 되는것
    console.log(this.name);
  },
  arrow: () => {
    //호출위치와 전혀 상관없이 this가 선언될때 this를 알 수 있음
    //자신이 선언된 함수 범위에서 this를 정의하기 때문
    console.log(this.name);
  },
};
he.normal(); //H.E
he.arrow(); //undefined
const timer = {
  name: "H.E",
  timeout: function () {
    // setTimeout(function () {
    //   //2초 뒤에 log창을 띄움
    //   console.log(this.name); //undefined
    // }, 2000);
    setTimeout(() => {
      //2초 뒤에 log창을 띄움
      console.log(this.name); //H.E
    }, 2000);
  },
};
timer.timeout();

JS ES6 Classes

// function User(first, last) {
//   this.firstName = first;
//   this.lastName = last;
// }
// User.prototype.getFullName = function () {
//   return `${this.firstName} ${this.lastName}`;
// };

class User {
  constructor(first, last) {
    //하나의 함수라고 보면 됨
    this.firstName = first;
    this.lastName = last;
  }
  getFullName() {
    //별도로 prototype 속성을 중간에서 사용하지 않아도 바로 prototype으로 만들어지는 메소드 정의
    return `${this.firstName} ${this.lastName}`;
  }
}
const she = new User("SH", "L");
const neo = new User("Neo", "Smith");

console.log(she.getFullName()); //SH L

JS 상속(확장)

class Vehicle {
  constructor(name, wheel) {
    this.name = name;
    this.wheel = wheel;
  }
}
class Bicycle extends Vehicle {
  //extends 확장(상속)을 의미
  //여기서는 Vehicle에 대한 정보를 Bicycle이라는 새로운 클래스로 확장, 상속해서 사용하겠다는 뜻
  constructor(name, wheel) {
    super(name, wheel);
    //extends 뒤에 확장된 클래스, 즉 여기서 Vehicle이 super이 있는 자리에서 실행됨
  }
}
class Car extends Vehicle {
  constructor(name, wheel, license) {
    super(name, wheel);
    this.license = license; //새로운 로직 추가(확장)
  }
}

댓글