[ javascript ] 함수의 또다른 기능 > javascript&jQuery

본문 바로가기

사이트 내 전체검색

javascript&jQuery

[ javascript ] 함수의 또다른 기능

작성일 21-02-11 02:08

페이지 정보

작성자 웹지기 조회 1,248회 댓글 0건

본문

함수의 또다른 기능

함수는 다른 변수처럼 사용된다.

변수에 값으로 할당 할 수 있다.

다른 함수에 인수로 전달 가능

다른 함수에 의해 반환될 수 있다.

First-class function

functions are treated like any other variable

can be assigned as a value to variable

can be passed as an argument to other functions.

can be returned by another function


1. 함수 표현(Function expression)

함수선언은 정의된것보다 먼저 호출이 가능한 표현식(hoisted 기능) : 함수

함수선은을 먼저 되어있어야 함수 실행이 가능한 표현식 : 익명함수

a function declaration can be called earlier than it is defiend. (hoisted)

a function expression is created when the execution reaches it.


const print = function() { //익명함수(anonymous function) - 함수에 이름이 없는 것

    console.log('print');

};

print(); //함수처럼 출력

const printAgain = print; //함수를 변수처럼 할당

printAgain(); //변수에 할당 되었으므로 함수처럼 호출 가능( function()을 가르키게 되므로 )

const sumAgain = sum; //함수로 설정된 sum(a, b)를 변수처럼 다시 할당도 가능

console.log(sumAgain(1,3)); //함수를 바라보고 있으므로 함수처럼 호출 가능


2. 함수표현식 callback함수(Callback function using function expression)

function randomQuiz(answer, printYes, printNo) {

    if(answer === 'love you') {

        printYes();

    } else {

        printNo();

    }

}


익명함수(anonymous function)

const printYes = function() {

    console.log('yes!');

};


정의함수(named function)

디버깅의 스택추적에 사용

재귀호출을 할 때 사용

better debugging in debugger's stack traces

recursions

const printNo = function print() {

    console.log('no!');

    //print(); //재귀호출(현재는 기능이 없으므로 무한반복됨)

};

randomQuiz('wrong', printYes, printNo);

randomQuiz('love you', printYes, printNo);


Arrow funcion

always anonymous

/* 아래 구문으로 간결하게 할 수 있다.

const simplePrint = function() {

    console.log('simplePrint!');

};

*/

const simplePrint = () => console.log('simplePrint!');

simplePrint();

/* 아래 구문으로 간결하게 할 수 있다.

const add = function(a,b) {

    return a+b;

}

*/

const add = (a,b) => a+b;

console.log(add(10,12));


즉시함수 호출방식(IIFE: Immediately Invoked Function Expression)

(function hello() {

    console.log('IIEF');

})();


Fun quiz time

function calculate(command, a, b)

command : add, substract, divide, multiply, remainder

const calculate = (command, a, b) => {

    switch(command){

        case '+' :

            console.log(a+b);

        break;

        case '-' :

            console.log(a-b);

        break;

        case '*' :

            console.log(a*b);

        break;

        case '/' :

            console.log(a/b);

        break;

        case '%' :

            console.log(a%b);

        break;

    }

};

calculate('+', 15, 10);

calculate('-', 15, 10);

calculate('*', 15, 10);

calculate('/', 15, 10);

calculate('%', 15, 10);

 


추천0

비추천 0

댓글목록

등록된 댓글이 없습니다.

전체 63건 1 페이지

이미지 목록

게시물 검색
Copyright © 즐거운 코딩 생활 ( funyphp ). All rights reserved.
PC 버전으로 보기