JS Essentials (basic)

HunGeun·2022년 4월 26일
0

HTML_CSS_JS

목록 보기
9/11

JS

Ecma International에서 표준화한 스크립트 언어가 ECMAScript, ES
자바스크립트를 표준화하기 위해 만들어짐

타입확인

console.log(typeof "hello"); //string
console.log(typeof 123); //number
console.log(typeof {}); //object
console.log(typeof []); //object
Object.prototype.toString.call({}) //object
Object.prototype.toString.call([]) //Array

Operator

- Arithmetic operator

산술 연산자
console.log(1 + 2)
console.log(5 - 7)
console.log(3 * 4)
console.log(10 / 4)

- Assignment operator

할당 연산자

let a = 2
a = a + 1 => a += 1
a = a - 1 => a -= 1 
a*=1
a/=1

- Comparison operator

비교 연산자

// === 일치 
const a = 1
const b = 1
console.log(a === b) //true 

const x = 2
const y = '2'
console.log(x === y) // false

// !== 불일치
const p = 1
const q = 3
console.log(p !== q) //true

//> < >= <=
초과, 미만, 이상, 이하

- Logical operator

논리 연산자

&& : and 전부 참인경우에만 ture
|| or 하나라도 참이면 참
! Not 부정연산자
true && true // true
true && false // false
true || true || false// true
false || false || false //false
!true // false

- Ternary operator

삼항 연산자

const a = 1 < 2
if (a) {
    console.log('참')
} else {
    console.log('거짓')
}

===
  
console.log(a ? '참' : '거짓')
//?를 기준으로 앞의 문장이 true 이면 : 앞부분을 실행하고 false 이라면 : 의 뒷부분을 실행한다

IF, Switch Statement

if, else if else 를 이용한 조건문
switch case break default 를 이용한 조건문

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

//조건문 (IF) if, else 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 statement)
const r = random()
switch (r) {
    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:
        console.log('rest...')
        console.log(r)
}

FOR Statement

반복문

for (시작조건; 종료조건; 변화조건) {}
// 종료조건이 false가 되면 종료한다

for (let i = 0; i < 3; i+= 1){
  console.log(i)
}
// 0 1 2 

Variable scope

변수 유효범위
변수가 유효하게 동작할수 있는 범위
let 과 const는 선언되어 있는 블럭내부가 유효범위이고,
var는 함수레벨에서 범위를 가진다

Type conversion, Truthy, Falsy

형 변환

const a = 1
const b = '1'

console.log(a === b) //false
console.log(a == b) //ture -> 동등연산자

if ('false') {
    console.log(123)
} //123

// Truthy(참 같은 값)
true {} [] 1 2 'false' -12 '3.13'

// Falsy(거짓 같은 값)
false, '' , null, undefined, 0, -0, NaN
NaN --> 1 + undefined, 

JS 함수

기본 구조

function sum(x,y) {
     console.log(x + y);
}
sum(1,3) //4
sum(4,12) // 16

arrow function

  • 화살표 함수
    기본 함수와 가장 큰 차이점 리턴 생략 가능
    매개변수가 하나만 있다면 () 생략 가능
    즉 {}와 () 생략 가능
    화살표 함수로 object를 반환 하려면 ()로 감싸준다.
//function
const double = function (x) {
    return x * 2
}
console.log('double: ', double(7))

// arrow function
const doubleArrow = (x) => {
    return x * 2
}
// () 와 return 생략가능
const doubleArrow = x => x * 2

// 객체 반환시 () 사용
const doubleArrow = x => ({ a: 1 })

IIFE

  • Immediately-Invoked Function Expression
    즉시 실행함수
const a = 8
//function
function double() {
    console.log(a * 2)
}
double();

//IIFE
//()의 위치는 무방하다.
(function () {console.log(a * 2)})()
or
(function () {console.log(a * 2)}())

Hoisting

  • 호이스팅
    함수 선언부가 유효범위 최상단으로 끌어올려지는 현상
var double2; // 함수표현식의 변수

function double() { // 함수선언문
        console.log("double");
}
double(); // double
double2(); // ERROR

double2 = function() { 
        console.log("double2");
}

timer function

  • 타이머 함수
    setTimeout(함수, 시간) : 일정 시간 후 함수 실행
    setInterval(함수, 시간) : 시간 간격마다 함수 실행
    clearTimeout(): 설정된 Timeout 함수를 종료
    clearInterval(): 설정된 Interval 함수를 종료
------------------------------------
setTimeout(() => {
    console.log('aaa')
}, 3000);  //시간단위: ms 3초후 aaa 출력
------------------------------------

const timer = setTimeout(() => {
    console.log('aaa')
}, 3000);  

const h1El = document.querySelector('h1')
h1El.addEventListener('click', () => {
    clearTimer(timer)
}) //timer 시간전에 h1태그 클릭시 timer 함수 중지

------------------------------------
const timer = setInterval(() => {
    console.log('aaa')
}, 3000);  //3초 마다 aaa출력

const h1El = document.querySelector('h1')
h1El.addEventListener('click', () => {
    clearInterval(timer)
}) // h1태그 클릭시 timer 함수 중지

callback function

  • 콜백 함수
    함수의 인자로 사용되는 함수
    콜백은 실행위치를 보장하는것에 자주 쓰임
function timeout(cb) {
    setTimeout(() => {
        console.log('hello')
        cb()
    }, 3000)
}
timeout(() => {
    console.log('done')
})

//timeout -> setTimeout -> after 3s -> console.log('hello') -> cb() -> console.log('done')

JS Class

Prototype

객체데이터는 메모리에 저장되며
객체안에 메소드가 있다면 객체갯수 만큼 함수가 생성됨
이러한 것들은 메모리 낭비로 이어지기 때문에
여러개의 객체데이터가 구조와 메소드의 로직도 같을때 생성자 함수를 사용
생성자 함수와 일반함수를 구별하기 위해 생성자 함수는 PascalCase를 이용해 명명함

//object안에서 속성과 메소드 합쳐서 Member라고 칭함
const myname = {
    firstname: 'hun',
    lastName: 'geun',
    getFullName: function () {
        return `${this.firstname} ${this.lastName}`
    }
}
console.log(myname) // object data
console.log(myname.getFullName())// hun geun

----------------------------------------

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

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

const myname = new User('hun','geun')
const amy = new User('amy', 'Clarke') 
const neo = new User('Neo', 'Smith')
//user -> 생성자 함수로 객체데이터 생성함
//myname, amy, neo가 인스턴스가 됨

console.log(myname.getFullName()) //hun geun 
console.log(amy) //user object data
console.log(neo)
// 평소에 {}를 통해서 객체를 생성하는것을 리터럴 방식이라 함

// 프로토 타입 
퍼스트 네임과 라스트네임은 그때그때 User라는 생성자 함수가 실행될때마다 다른 내용이 들어가기 때문에 통일 힘듬
하지만 getFullName과 같이 로직이 똑같은 경우 프로토타입을 이용해서 공통적인것을 통일화해서 메모리 관리 가능
자바스크립트는 수많은 프로토타입으로 이루어진 언어

this

function는 호출 위치에서 this 정의
Arrow function는 자신이 선언된 함수 범위에서 this 정의
example 1)

//function 
const timer = {
  name: 'Hun!!',
  timeout: function () {
    setTimeout(function () {
      console.log(this.name)
    }, 2000)
  }
}
timer.timeout()
// undefined

--------------------
//Arrow function
const timer = {
  name: 'Hun!!',
  timeout: function () {
    setTimeout(() => {
      console.log(this.name)
    }, 2000)
  }
}
timer.timeout()
//Hun!!

example 2)

const heropy = {
    name: 'Heropy',
    normal: function () {
        console.log(this.name)
    },
    arrow: () => {
        console.log(this.name)
    }
}
heropy.normal() //hun
heropy.arrow() // undefined

es6 classes

//js 
function user(first, last) {
    this.firstName = first
    this.lastName = last
}
user.prototype.getFullName = function () {
    return `${this.firstName} ${this.lastName}`
}
----------------------------------------
//es6의 class 형태
class User {
    constructor(first, last) {
        this.firstName = first
        this.lastName = last
    }
    getFullName() { //prototype 사용 안해도 됨
        return `${this.firstName} ${this.lastName}` 
    }
}

상속/확장

이미 정의 되어있는 class에서 상속/확장 (살을붙혀서) 추가로 기능을 붙혀서 사용하는것
super: 확장된 원래 클래스에서 super부분이 작동함. 즉 기존의 정의되어 있는 인수를 사용함

//원래 클래스
class Vehicle {
    constructor(name, wheel) {
        this.name = name
        this.wheel = wheel
    }
}
const myVehicle = new Vehicle('운송수단', 2)


// 상속**/확장
class Bicycle extends Vehicle { //확장, 상속
    constructor(name, wheel) {
        super(name, wheel)
    }
}
const myBicycle = new Bicycle('삼천리', 2)
const daughtersBicycle = new Bicycle('세발', 3)


// 상속/확장**
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)

0개의 댓글