[패스트캠퍼스] 프론트엔드 강의 학습후기 5주차(1)

양정현·2022년 10월 13일
0

패스트캠퍼스

목록 보기
5/8

ecma 스크립트

  • ES 라고도 부를 수 있음, 자바스크립트를 표준화 해주는 국제 표준화 기구 의미
  • 자바스크립트가 표준화가 된 것 = 에크마 스크립트
  • ex) ES6, ES2015 > 자바스크립트의 버전

데이터 타입 확인

  • import getType from './getType'
console.log(typeof "hello world") // string 출력
console.log(typeof 123) // number 출력
console.log(typeof true) // boolean 출력
console.log(typeof undefined) // undefined 출력
console.log(typeof null) // object 출력
console.log(typeof {}) // object 출력
console.log(typeof []) // object 출력

typeof 를 사용하면 어떤 타입인지 나오지만 뭉덩이로 object 라고 표시가 될 수 있음
>> 타입을 반환하는 함수 만들기

function getType(data){
	return Object.prototype.toString.call(data).slice(8, -1)
    // slice > '[object'와 끝']' 삭제
}

! 함수를 사용한 후 console.log 변화

console.log(getType(123)) // Number 출력 
console.log(getType(false)) // Boolean 출력
console.log(getType(null)) // Null 출력
console.log(getType({})) // Object 출력
console.log(getType([])) // Array 출력
  • 매번 이렇게 함수를 사용할 수는 없으니 함수만 따로 분리하여 파일 생성 가능
  • 생성한 파일엔 함수 앞 export default 기재
  • 연결하려는 파일엔 import getType from './연결한 파일 명(확장자X)' 기재

비교/논리 연산자

  • 산술 연산자(arithmetic opearator)
    • 1 + 2
    • 5 - 7
    • 3 * 4
    • 10 / 2
  • 나머지 연산자
    • console.log(7 % 5) // 2 출력
  • 할당 연산자(assignment operator)
    • const test = 2 : = 라는 기호가 할당 연산자
    • const : 재할당 불가
    • let : 재할당 가능
    • ab += 1 과 a = a + 1 은 같음
  • 비교 연산자(comparison operator)
    • const a = 1, const b = 1 로 할당했을 때 console.log(a === b ) // ture 출력

    • type도 똑같아야 true를 출력함

      < 비교 연산자 함수 >
      
      function isEqual(x, y){
      	return x === y
      }
      
      console.log(isEqual(1,2)) // false 출력
    • !== : 서로가 다른 것인지 확인해주는 연산자

    • a < b : a가 b보다 작을 때 true 출력

    • a >= b : a가 b보다 같거나 클 때 true 출력
      = 기호 앞에 꺽새 표시가 있으면 문법 오류

    • && : 그리고 AND, 나열된 것이 모두 true 인 경우에만 true 출력.
      하나라도 false 인 경우 false 출력

    • || : 또는 OR, 나열된 것들 중 true 가 하나라도 있으면 true 출력.
      나열된 값 모두가 false인 경우에만 false 출력

    • ! : 부정 NOT 연산자. 값의 밥ㄴ대되는 것이 출력이 됨

삼항 연산자(ternary operator)

  • 항이 세개인 것
  • const a = 1 < 2
    a ? '참' : '거짓' // ? , ", " 항이 세개
    값이 ture면 : 앞부분 실행
    값이 false면 : 뒷부분 실행

조건문

export default function random(){
	return Math.floor(Math.random() * 10)
}   

<조건문 if else>
const a = random()

if(a === 0){
	console.log('a is 0')
} else if(a === 2){
	console.log('a is 2')
} else if(a === 4){
	console.log('a is 4')
} else {
	console.log('rest...')
}

<조건문 switch>
switch(a){
	case 0:
		console.log('a is 0')
    	break
    case 2:
    	console.log('a is 2')
        break
    case 4: 
    	console.log('a is 4')
        break
    default: // if 문의 else 문, break도 사용하지 않아도 됨
    	console.log('rest...')
}

! 조건을 사용하려고 할 때 특정한 값으로 분기처리를 하고 있을 땐
if문 보다는 switch문이 훨씬 더 직관적으로 보일 수 있다

반복문 for

  • for(시작조건; 종료조건; 변화조건){}
    for(let i = 0; i < 3; i += 1){
    	/*
       	 시작조건: let i = 0 (통상적으로 권장되는 변수 이름 i)
         종료조건: i가 3보다 작지 않은 경우 종료가 됨
         변화조건: i에 계속 +1을 할당함
       */
       
       console.log(i) // 0,1,2 출력
    }

변수 유효범위

  • let, const : 블록 레벨
    • 중괄호 내에서 유효한 범위를 가질 수 있음
      console.log(a)가 어디에 위치하느냐에 따라 출력 값이 달라짐
  • var : 함수 레벨
    • 함수 내에서 어디서든 사용할 수 있음
      console.log(a)가 어디에 위치하느냐에 상관없이 출력값이 똑같음
    • 개발자가 의도한 것과 다르게 나올 수 있음
      유효범위 안에서 변수가 유효하개 동작하도록 함

형 변환

  • const a = 1 / const b = '1'
    • console.log(a === b) // false 출력
    • console.log(a == b) // 동등 연산자, true 출력
    • 동등 연산자 : 안쓰는 것을 권장
      의도하지 않게 다른 값이 같다고 나올 수 있기 때문
      형 변환이라는 것이 일어나며 타입 변화가 일어난 것을 비교하기 때문에 의도한 것처럼 나오지 않을 수 있음

함수 복습

function sum(x,y){ // x, y 매개 변수
	return x + y
}

const a = sum(1,3) // 1, 3 인수

console.log(a) // 4 출력
console.log(sum(1, 3)) // 4 출력 
  • 계속 함수를 호출하는건 변수 사용보다 덜 효율적임
  • 함수의 결과가 반복적이면 변수에 담는 것이 좋고, 단일적 사용이면 함수 호출이 더 효율적이다
  • 익명함수/기명함수
    • 익명함수 : const a = function ...
    • 기명함수 : function a () ...
  • return 키워드 : 함수 내부에서 return 키워드를 사용할 때 return이 있는 곳에서 함수가 종료됨
  • argument : 매개변수를 지정하지 않아도 내부에서 쓸 수 있도록 만들어져있고 객체로 변환 해줌

화살표 함수

  • () => {} vs function(){}
const double = function(x){
	return x * 2
}
console.log('double:', double(7))

const doubleArrow = x => x * 2
console.log('doubleArrow:', doubleArrow(7))
  • 일부 내용을 생략해서 축약형으로 쓸 수 있는 함수
  • 실행문 부분을 중괄호로 감싸면 반환 되지가 않음
    return을 추가해주어야 반환이 가능
  • 실행문을 return 과 중괄호가 생략되어야 화살표 함수 사용 가능
  • const test = (x, y) => x + y
    매개변수가 두 개 일 경우에는 소괄호 사용
  • 중괄호 부분을 소괄호로 감싸야 객체 데이터 반환이 가능함

즉시 실행 함수 (IIFE)

  • 함수를 만들자마자 바로 실행하여 동작시키는 함수
const a = 7
function double(){
	console.log(a * 2)
}
double(); // 즉시 실행함수를 실행할 땐 앞 함수에 세미클론 넣어주어야 함

(function(){
	console.log(a * 2)
})(); // 소괄호 위치 확인, 14 출력
(function(){
	console.log(a * 2)
}()); // 소괄호 위치 확인, 14 출력

호이스팅

  • 함수 선언부가 유효범위 최상단으로 끌어올려지는 현상
  • 함수 호출을 익명 함수 앞에 두면 오류가 뜸
  • 기명 함수로 함수를 선언한 경우에는 함수 호출이 위에 있어도 제대로 출력됨
  • 함수 안에 복잡한 내용이 들어갈 때 사용하기 용이함

타이머 함수

  • setTimeOut(함수, 시간): 일정 시간 후 함수 실행
  • setInterval(함수, 시간): 시간 간격마다 함수 실행
  • clearTimeout(): 설정된 Timeout 함수를 종료
  • clearInterval(): 설정된 Interval 함수를 종료
setTimeout(function (){
  console.log("hello!")
}, 3000) // 3초 뒤에 console에 헬로우 출력

const timer = setInterval(() => {
  console.log("화살표 함수")
}, 3000)

const h1El = document.querySelector("h1")
h1El.addEventListener('click', () => {
  clearInterval(timer)
})

콜백(callback)

  • 함수의 인수로 사용되는 함수
  • 실행위치를 보장하는 용도로 활용 된다
function timeout(cb){
  setTimeout(() => {
    console.log("hello")
    cb()
  }, 3000) 
}

timeout(() => {
  console.log("done!")
})

생성자 함수

  • 일일히 객체데이터를 만들면서 효율성이 떨어질 때 함수의 로직이 똑같을 때 자바스크립트의 클래스를 사용
const heropy = {
  firstName : 'heropy',
  lastName : 'Park',
  getFullName: function(){
    return `${this.firstName} ${this.lastName}` 
  }
}
console.log(heropy.getFullName())

const amy = {
  firstName: "Amy",
  lastName: "clarke",
  getFullName: function(){
    return `${this.firstName} ${this.lastName}`
  }
}

console.log(amy.getFullName())

const neo = {
  firstName: "Neo",
  lastName: "Smith",
  getFullName: function(){
    return `${this.firstName} ${this.lastName}`
  }
}

console.log(neo.getFullName())

function User(first, last){ // 파스칼 케이스
  this.firstName = first
  this.lastName = last
}

User.prototype.getFullName = function (){
  return `${this.firstName} ${this.lastName}`
}

const heropy = new User("heropy", "park") // 변수 > 인스턴스
const amy = new User("Amy", "clarke")
const neo= new User("neo", 'smith')

console.log(heropy.getFullName()) // user라는 객체데이터 출력
console.log(amy.getFullName())
console.log(neo.getFullName())

const hreopy = {} >> 리터럴 방식
  • prototype 타입 기반의 프로그래밍 언어
    프로토타입을 사용해서 new 라는 키워드와 함께 생성자 함수로 인스턴스를 만들어주는 것을 자바스크립트의 클래스라고 함
  • new라는 키워드를 사용하여 생성한 함수 = 생성자 함수
  • 하나의 객체 데이터가 생성이 됨

this

  • 일반 (normal) 함수는 호출 위치에 따라 this 정의
  • 화살표(arrow) 함수는 자신이 선언된 함수 범위에서 this 정의
const heropy = {
  name: 'heropy',
  normal: function (){
    console.log(this.name)
  },
  arrow: () => {
    console.log(this.name)
  }
}

heropy.normal() // heropy 출력
heropy.arrow() // undefined 출력

const amy = {
  name: 'Amy',
  normal: heropy.normal, // ()가 없음 > 호출하는 것이 아님
  arrow: heropy.arrow // heropy의 데이터 자체가 할당이 되는 것을 뜻함
}

amy.normal() // amy 출력
amy.arrow() // undefined 출력


function User(name){
  this.name = name
}
User.prototype.normal = function(){
  console.log(this.name)
}
User.prototype.arrow = () => {
  console.log(this.name)
}

const jeonghyun = new User('jeonghyun')
jeonghyun.normal() // jeonghyun 출력
jeonghyun.arrow() // undefined 출력

const timer = {
  name: "name",
  timeout: function (){
    setTimeout(() => {
      console.log(this.name)
    }, 2000)
  }
}
timer.timeout() // name 출력
  • 화살표 함수가 자신이 만들어진 함수 범위에서 정의가 되기 때문에 화살표 함수를 이용해야 this.name이 출력
  • 일반 함수로 this를 정의했을 땐 undefined 출력
  • 타이머 함수와 this를 쓸 경우에는 화살표 함수를 쓰는 것이 더 용이함

ES6 classes

  • 자바스크립트는 클래스 라는 속성을 사용하여 ES6라는 것을 활용할 수 있음
const heropy = {
   name : 'Heropy',
   normal/*function*/(){
     /*
       function 생략 가능
     */
     console.log(this.name)
  },
  arrow: () => {
    console.log(this.name)
  }
}

heropy.normal()
heropy.arrow()

function User(first, last){
   this.firstName = first
   this.lastName = last
 }

 User.prototype.getFullName = funciton(){
   return `${this.firstName} ${this.lastName}`
 }

class User {
  constructor(first, last){
    this.firstName = first
    this.lastName = last
  }
  getFullName(){
    return `${this.firstName} ${this.lastName}`
  }
}

상속(확장)

  • extends : 확장
  • 이미 정의가 되어있는 내용을 확장(상속)해서 사용 가능
  • extends 키워드를 통해 특정한 클래스를 가지고 와서 상속 확장 가능, 확장된 클래스는 super라는 함수를 통해 내부에서 내가 원하는 위치에서 손쉽게 실행할 수 있다는 개념
class Vehicle {
  constructor(name, wheel){
    this.name = name
    this.wheel = wheel
  }
}
const myVehicle = new Vehicle('운송수단', 2)
console.log(myVehicle)

class Bicycle extends Vehicle{
  constructor(name, wheel){
    super(name, wheel)
  }
}

const myBicycle = new Bicycle('삼천리', 2)
const daughtersBicycle = new Bicycle('세발', 3)
console.log(myBicycle)
console.log(daughtersBicycle)

class Car extends Vehicle{
  constructor(name, wheel, license){
    super(name, wheel)
    this.license = license /* 기존에 있는 내용에 확장하여 추가 */
  }
}
const myCar = new Car('벤츠', 4, true)
const daughtersCar = new Car('포르쉐', 4, false)

console.log(myCar)
console.log(daughtersCar)

0개의 댓글