Notice
Recent Posts
Recent Comments
Link
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

JS Coding

[JavaSciprt] 자바스크립트에서 사용되는 "This" 본문

JavaScript

[JavaSciprt] 자바스크립트에서 사용되는 "This"

JSKJS 2023. 11. 10. 15:02
<!DOCTYPE html>
<meta charset="UTF-8">
<h1 id="js">재성 오케잉</h1>
<button id="bind"> 억지 bind 예제 버튼</button>
<script>
    //사용이 권장 되지는 않는다. (제대로 사용이 안되서)
    // document.write("<h1>write 에 대한 설명</h1>");
    /*
    기본 함수를 사용할줄 알면 이렇게 사용 가능.

    function print(msg){
        document.write(msg);
    }
    */

    // var print = document.write; //문법적으로 이렇게 사용 가능.
    // 이렇게 사용하면 document.write 내에는 this가 내장되 어있는데
    // print()로 넣게 되면 print 앞 window가 있기에
    // this가 window를 가라키게 되어서 문법은 맞으나 불법적?인
    // 사용이 되어 에러가 난다.
    // 제대로 사용하려면
    var print = document.write.bind(document);
    // 이렇게 bind를 붙여 사용해야 에러가 없다.


    print("<h1>함수객체로 만들어 사용된 write</h1>");
    print("<h1>매번 document.write로 길게 안써도 된다.</h1>");

    const myBind = document.querySelector("#bind");

    function fClick(pName){
        alert(`${pName}님 저 누르셨나요}`);
        alert(this.merong);

        // 스크립트 내에서는 순서대로 나오면서
        // 다같이 출력 되지만
        // 함수 안에서 사용 될 경우에는 다 사라지고
        // write 내 문자만 출력이 된다.
        // document.write("<h1>write 에 대한 설명</h1>");
    }

    // fClick에 ()를 붙이면 함수 실행 명령이 되기 때문에
    // 버튼이 누르기도 전에 실행이 되버린다.
    // 이렇게 바로실행이 안되고 버튼을 눌렀을때 실행 시키고 싶다면
    // bind를 사용하면 된다.
    myBind.addEventListener("click", fClick.bind(
        {
        merong:"재성메롱"
        },
        "이수정"
    ));


    //call, apply, bind라는 function객체의 메소드로
    // function 안의 this값을 개발자가 직접 지정이 가능해짐 **

    function fThis(pArg1, pArg2, pArg3){
        console.log("체크 : ",this);    // ? window
        console.log("매개변수 : ",pArg1,pArg2,pArg3);
    }

    //객체 선언
    var sujin = {
        name : "수진 전",
        mood : "무표정"
    }

    fThis.call(document.querySelector("#js"),"김","재","성");
    fThis.apply(sujin,["전","수","진"]);
    // apply는 무조건 매개변수를 배열에 담아서 넘겨야 함.
    // 그 외는 call과 똑같다.
   
    // bind는 함수를 실행 안시키고
    // 내부적으로 this값과 매개변수가 세팅된 함수를 만들어서
    // 함수(포인터)를 되돌려 준다.
    console.log(fThis.bind(document,"난","HTML문서"));

    /*

    fThis();
    // 참조(Reference)로 메소드 추가
    sujin.msg = fThis;
    //this가 가리키는 값이 달라짐
    // 개발자들이 반발 ! , 누굴 가리키는 몰라서 개발이 어려워 대책이 필요함.
    // sujin.msg();


    // 위에 껀 요것과 같음 ! , 전역함수 선언은 window 객체에
    // 메소드를 추가하는 것과 같다
    // window.fThis = function(){
    //     console.log("체크 : ",this);
    // }

    // window.fThis(); //fThis();

    // var myName ="김재성";
    // window.myName = "김재성";   // 위와 동일한 의미
    // alert(myName);
    // let 과 const는 기존 var 와는 저장되는 context가 다르다.

    // let myName2 = "유선영 디버깅 못함";
    // alert(window.myName2);

*/
</script>