[JavaScript] this와 bind

    반응형
    SMALL
    반응형
    SMALL

    this -> {} : 어떤 객체를 가르키는 키워드, this가 가리키는 객체는 상황에 따라 바뀐다.

     

    this는 함수를 호출객체이다

    1. 전역 문맥

    전역적 문맥에서 this에 접근하면 this는 윈도우 객체가 된다.

    ( 엄격모드 활성화 ( 'use strict'; ) 시에도 상관 없이 윈도우 객체를 가리킨다 )

    if (true) {           // 1
      console.log(this);
    }
    
    
    console.log(this);    // 2
    
    
    'use strict';         // 3
    
    console.log(this);

     

     

     

    함수 내부의 this : 함수 호출 방법에 따라 값이 달라짐

     

    1) this : 윈도우 객체

    전역적으로 함수를 호출하는 것은 window.main();과 같음

    >> "this 는 함수(main)를 호출한 객체(window)이다"

    function main() {
      console.log(this);
    }
    
    main(); // window.main(); 생략

     

    ** 'use strict'; 사용 시 this의 값이 undefined됨

    엄격모드 시 main()이 아닌 window.main()이라고 직접적으로 호출해야 함.


    2. 객체의 메서드

    메서드 : 객체(object)의 속성(main)에 넣어진 함수를 의미

    ** 함수 내부의 this는 함수(main)를 호출한 객체(object)이다 -> this의 값 : object

    객체의 다른 속성에 접근할 때 유리함 (object를 가리키고 있으므로 console.log(this.name); 시 name에 접근 가능)

     

    + 메서드 안에서 this를 사용하는 경우는 객체의 속성에 접근하기 위함 (ex. console.log(this.name + "입니다.";)

    const object = {
      name: 'chaenilog',
      main: function () {
        console.log(this);
      },
    };
    
    object.main();

     

    main함수 먼저 정의 후 객체를 생성해 객체의 구성원으로 main 포함시켜도 똑같이 this는 object 객체가 된다

    function main() {
      console.log(this);
    }
    
    const object = {
      name: 'chaenilog',
      main, // 키, 값이 같으면 하나로 생략가능
    };
    
    object.main();
     


     

    this 값 : 윈도우 객체 출력

    더이상 main2 함수를 호출한 객체는 object가 아니고 전역적으로 호출된 함수이기 때문

    const object = {
      name: 'chaenilog',
      main: function () {
        console.log(this.name);
      },
    };
    
    object.main();
    
    //추가
    const main2 = object.main;
    main2();

     

    this 값 : smallObject

    function main() {
      console.log(this);
    }
    
    const object = {
      name: 'chaenilog',
      smallObject: {
        name: 'small chaenilog',
        main,
      },
    };
    
    object.smallObject.main();


    3. bind()

    this 값 : 윈도우 객체

    function main() {
      console.log(this);
    }
    
    main();

    this 값 : main

    function main() {
      console.log(this);
    }
    
    const mainBind = main.bind({ name: 'hi' });
    mainBind();

     


    아무리 새 object를 만들고 호출해도 this 값 고정

    function main() {
      console.log(this);
    }
    
    const mainBind = main.bind({ name: 'hi' });
    mainBind();
    
    // 아무리 새 object를 만들고 호출해도 this 값 고정
    const object = {
      mainBind,
    };
    object.mainBind();

     

    ** 이미 bind 된 걸 또 한 번 bind 할 수 없다!

     


    const object = {
      name: 'chaenilog',
      main: function () {
        console.log(this);
      }.bind({ name: '멋진 객체' }),
    };
    
    object.main();


    4. 이벤트 처리기

    this 값 : 버튼

     

    index.html

    <!DOCTYPE html>
    <html>
      <head>
        <title>My Page</title>
        <script defer src="index.js"></script>
      </head>
      <body>
        <button id="btn">버튼</button>
      </body>
    </html>

     

    index.js

    const button = document.getElementById('btn');
    
    button.addEventListener('click', function () {
      console.log(this);
    });

     

     

    확인하기 :

      console.log(event.target === this);

     

    >> true 출력!

     

     

     

     

    .

    .

    .

     

     

    https://www.youtube.com/watch?v=j6VkGimAs-E&list=PLZ5oZ2KmQEYiGLIDlsTQR_wdfCH9ZD6lx&index=2

     

     

     

     

     

    반응형
    LIST

    'Front-end > JavaScript' 카테고리의 다른 글

    [JavaScript - 비동기 시리즈 1] 동기 VS 비동기  (0) 2025.03.22
    [JavaScript] Callback 함수  (0) 2025.03.22
    [JavaScript] 일반함수 vs 화살표 함수 + this 비교  (0) 2025.03.18
    JS 실습 8-4  (0) 2022.12.11
    JS 실습 8-3  (0) 2022.12.11

    댓글