11. 함수 리터럴과 익명함수
1) 리터럴
: 자바 스크립트에서 데이터를 만드는 방법은 크게 두가지로,
리터럴 방식과 객체 방식 두가지가 있다.


타입 리터럴 방식  
숫자  var num=10;  var num = new Number(10);
문자 var name="abc" var name = new String("abc");
불린 var play= true; var play = new Boolean(true);
배열  var arr=[1,2,3];  var arr = new Array(1,2,3);


2) 함수 리터럴
: 함수 이름을 주지 않고 만들면 됨.

#1. 일반적인 방법
function hello(){
.....
}

#2. *리터럴*
var hello = function(name){
....
}
#3. 객체방식(잘안씀)
var hello = new function("name","실행할 명령문들");

3) 익명함수
: 리터럴 방식의 함수를 익명함수라 한다.
호이스팅 불가능
일반함수 : 재사용 많이   할 경우 
익명함수 : 재사용 비중이 적거나, 값처럼 정의해서 넘겨줘야할 경우

익명 함수 활용 전  익명 함수 활용 후
function hello(){
    alert("안녕하세요");
}
$("#btn").click(hello);
$("#btn").click(function(){
    alert("안녕하세요");
});

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    
    <button id="btn">클릭</button>
    <script>
        // 리터럴
        var hello = function(name) {
            console.log(name + "님 배고프신가요?");
        }
        
        hello("토피"); 
        
        // 익명함수 
        $(document).ready(function(){
            $("#btn").click(function(){
                alert("안녕하세요");
            });        
        }); 
   
    </script>
    
</body>
</html>

 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    
    <script>
        //console.log(a);
    
        //a = 10;  // 전역변수로 선언+대입 해줌 
        //console.log(a);
    
        var a = "global";
        
        function f() {
            a = "local"; // 함수 안에서 var 생략하면 전역으로 선언됨.
            console.log("f : " + a);
        }
        f(); 

        console.log(a);
        
    </script>
     
</body>
</html>

+ Recent posts