js함수의 특징 3가지

1. 일급객체 : 파라미터로 던질 수 있고 리턴값으로 사용할 수 있다.
2. 객체 지향언어에서 new는 안에 컨텍스트를 만들어 자기 자신을 this로 리턴시킴
    (function 을 new 하면 this로 던져주는 것과 같다 )
3. argument (오버로딩이 불필요)



Button Count

<html>
    <body>
        <button id="button1">버튼1 </button>
        <button id="button2">버튼2</button>
    </body>

    <script>
    function count(){
        var count = 0;

        function showcount (){
            count ++;
            console.log("클릭",count)
        }
        this.sohowcount = shwcount
    }

    let button1 = new count();  
    let button2 = new count();
        document.querySelector("#button1").addEventListener("click",button1.showcount)
        document.querySelector("#button2").addEventListener("click",button2.showcount)

    </script>
</html>



new로 객체를 생성 할 때 주의점 
 : function으로 new를 할 때 return으로 던지지 말 것

function test (){
    function test(){
        console.log("테스트1입니다.")
    }
    function test2(){
        console.log("테스트2입니다.")
    }

    // return  {} 이렇게 던지면 안되고 

    this.test = test    // this를 이용 
    this.test2 = test2
}

new test();  //  test {test: ƒ, test2: ƒ}

test();   // undefined


var a  = new test();
console.log(a.test())  // 테스트1입니다.



return 으로 던지면 

function test (){
    function test(){
        console.log("테스트1입니다.")
    }
    function test2(){
        console.log("테스트2입니다.")
    }

     return  {test,test2} 
}

test();    // {test: ƒ, test2: ƒ}



button count & reset 

<html>
    <body>
        <button id="btn-count1">버튼1 </button>
        <button id="btn-count2">버튼2</button>
        <div id="count1"></div>
        <div id="count2"></div>
        <button id="btn-reset1">리셋1</button>
        <button id="btn-reset2">리셋2</button>
    </body>
    <script>
        function counter(options){
            let __options = {name:"디폴트"};
            this._options = Object.assign(__options,options); 
            let count = 0;
            document.getElementById(this._options.id).addEventListener("click" , e =>{
                count++;
                document.getElementById(this._options.display).innerText = count;
            //   console.log(count)
            });

            document.getElementById(this._options.reset).addEventListener("click" , e =>{
                count = 0;
                document.getElementById(this._options.display).innerText = count;
            //   console.log(count)
            });
    }

    const options = {
        id : "btn-count1",
        display:"count1",
        name : "카운터앱1",
        reset : "btn-reset1"
    }

    const options2 = {
        id : "btn-count2",
        display:"count2",
        name : "카운터앱2",
        reset : "btn-reset2",
    }
        const ci = new counter(options);
        const ci2 = new counter(options2);
    </script>
</html>

'업무중필요모음 > Snippet' 카테고리의 다른 글

[JAVA] - GSON  (0) 2024.08.12
[JAVA] - JsonObject  (0) 2024.08.12
[JAVA] - JSON  (0) 2024.08.12
[JAVA] - RestTemplete  (0) 2024.08.12
[Java] try-with-resource  (0) 2024.08.12

+ Recent posts