개발 일기 8월 6일 (자바스크립트 -함수)

백승찬·2023년 8월 5일

개발일기장

목록 보기
3/4

선언과 표현 그리고 호이스팅

// 함수

// 함수 선언문(Declaration)
function hello() {}

// 함수 표현식(Expresssion)
const hello = function() {}

// 호이스팅(Hoisting)  // 호이스팅은 함수 선언부가 유효범위 최상단으로 끌어올려지는 현상을 말합니다.

hello()

function hello(){
    console.log('Hello');
}  // 호이스팅 현상은 함수 선언에만 가능하고 함수 표현식에서는 안된다.


hello()

const hello = function(){
    console.log('hello');
}

반환 및 종료

// 반환 및 종료

function plus(num){
    if(typeof num !== 'number'){
        console.log('숫자를 입력해주세요!');
        return 0
    }
    return num + 1
}

console.log(plus(7));
console.log(plus(2));
console.log(plus());

매개변수 패턴

// 매개변수 패턴(Parameter pattern)

//// 기본값(Default value)

function sum(a, b = 1){
    return a + b
}

console.log(sum(1, 2));
console.log(sum( 7));


//// 구조 분해 할당(Destructuring assignment)

const { get } = require("lodash")

const user = {
    name : 'chan',
    age : 27,
    // email : 'chchch@naver.com'
}

function getName({name}){
    return name
}

function getEmail({email = '이메일이 없습니다.'}){
    return email
}

console.log(getName(user));
console.log(getEmail(user));


const fruits = ['Apple', 'Banana', 'Cherry']
const numbers = [1,2,3,4,5,6,7]

function getSecondItem([,b]){
    return b
}

console.log(getSecondItem(fruits));
console.log(getSecondItem(numbers));

//// 나머지 매개변수(Rest Parameter)

function sum(...rest){
    return rest.reduce(function(acc, cur){
        return acc + cur
    }, 0)
}

console.log(sum(1,2,));
console.log(sum(1,2,3,4,5));
console.log(sum(1,2,3,4,5,6,7,8,9,10));

화살표 함수

// 화살표 함수(Arrow function)

// function sum() {}
// const sum  = function(){}
// const sum = () => {}

// function sum(a,b){
//     return a + b
// }

const sum = (a, b) =>  a + b 

console.log(sum(1,2));
console.log(sum(10,20));

const a = () => {}
const b = x => {}
const c = (x, y) => {}
const d =  x => x * x
const e = x => x * x
const f = x => {
    console.log(x * x);
    return x * x
}

const g = () => { return  { a : 1}}
const h = () => {{ a : 1}}
const i = () => { return [1,2,3]}
const j = () => [1,2,3]

즉시실행함수(IIFE)

// 즉시실행함수(IIFE, Immediately-Invoked Function Expression)

const a = 7

const double = () => {
    console.log(a * 2);
}

double();

(() => {
    console.log(a * 2);
})()


;(() => {})() //(F)()
;(function () {})() // (F())
;(function () {}())() //(F())
;!function () {}() // !F()
;+function () {}() // +F()


;((a,b) => {
    console.log(a.innerWidth);
    console.log(b.body);
})(window, document)

콜백

// 콜백(Callback) 함수가 실행될 떄 인수로 들어가는 또 하나의 함수

const a = callback => {
    callback()
    console.log('A');
}

const b = () => {
    console.log('B');
}

a(b)


const sum = (a,b,c) => {
    setTimeout(() => {
        c(a+b)
    }, 1000)
}

sum(1,2,value => {
    console.log(value)
}) 
sum(3,5,value => {
    console.log(value)
}) 


const loadImage = (url, cb) => {
    const imgEl = document.createElement('img')
    imgEl.src = url
    imgEl.addEventListener('load', () => {
        setTimeout(() => {
            cb(imgEl)
        },1000)
    })
} 

const containerEl = document.querySelector('.container')
loadImage('https://www.gstatic.com/webp/gallery/4.jpg',(imgEl)=> {
    containerEl.innerHTML= ''
    containerEl.append(imgEl)
})

재귀

// 재귀(Recurslive)  자기 자신을 무한정 생성 그래서 조건을 만들어줘야한다.

let i = 0

const a = () =>{
    console.log('A');
    i++
    if(i<4){
        a()
    }
}

a()

const userA = {
    name:'A',
    parent:null
}

const userB = {
    name:'B',
    parent:userA
}

const userC = {
    name:'C',
    parent:userB
}

const userD = {
    name:'D',
    parent:userC
}

const getRootUser = user => {
    if(user.parent) {
        return getRootUser(user.parent)
    }
    return user
}

console.log(getRootUser(userD));

// 재귀함수는 무한으로 반복실행한다.

호출 스케줄링

// 호출 스케줄링(Scheduling a function call)자바스크립트에서 함수에 호출을 지연하거나 반복하는 방법

const hello = () => {
    console.log('Hello~');
}

const timeout = setTimeout(hello, 2000)

// clearTimeout 타이머를 해제한다.

const h1El = document.querySelector('h1')
h1El.addEventListener('click', () => {
    clearTimeout(timeout)
})


const hello = () => {
    console.log('Hello~');
}

const timeout = setInterval(hello, 2000)

// clearTimeout 타이머를 해제한다.

const h1El = document.querySelector('h1')
h1El.addEventListener('click', () => {
    console.log('Clear');
    clearInterval(timeout)
})

// setInterval 반복할 떄 사용
// clearInterval 해제

this

// this
//// 일반 함수의 this는 호출 위치에서 정의
//// 화살표 함수의 this는 자신이 선언된 함수 (렉시컬) 범위에서 정의

const user = {
    firstName : 'baek',
    lastName : 'seungchan',
    age: 27,
    getFullName: function(){
        return `${this.firstName} ${this.lastName}`
    }
}

console.log(user.getFullName());



function user(){
    this.firstName = 'hello'
    this.lastName = 'bye~~'

    return{
        firstName : 'baek',
        lastName : 'seungchan',
        age: 27,
        getFullName: () => {
            return `${this.firstName} ${this.lastName}`
        }
    }
}

const u = user()
console.log(u.getFullName());



function user(){
    this.firstName = 'hello'
    this.lastName = 'bye~~'

    return{
        firstName : 'baek',
        lastName : 'seungchan',
        age: 27,
        getFullName() {
            return `${this.firstName} ${this.lastName}`
        }
    }
}

const lewis = {
    firstName: 'easy',
    lastName: 'hard'
}

const u = user()
console.log(u.getFullName());
console.log(u.getFullName.call(lewis));

// 렉시컬(Lexical)이란 함수가 동작할 수 있는 유효한 범위를 의미합니다.


const timer = {
    title: 'TIMER!',
    tiemout(){
        console.log(this.title);
        setTimeout(()=>{  
            console.log(this.title);
        },2000)  // 일반함수로 사용할 경우 undefined가 나온다는 점 주의해야한다. 
    }
}

timer.tiemout()
profile
신은 인간에게 선물을 줄 때 시련이라는 포장지에 싸서 준다. 선물이 클수록 더 큰 포장지에 싸여있다. - 브라이언 트레이시 -

1개의 댓글

comment-user-thumbnail
2023년 8월 5일

많은 것을 배웠습니다, 감사합니다.

답글 달기