자바 스크립트에서 "이것"이란 무엇입니까?

2458 단어 javascriptthis
이 게시물에서 우리는 this 키워드가 다양한 조건에서 무엇을 참조하는지 탐구하고 거기에서 키워드와 자바스크립트에서 어떻게 작동하는지 이해합니다.
this 키워드는 다음을 가리킬 수 있습니다.
  • object 메서드 내에서 참조될 때 개체입니다.
  • window 객체 - 함수 내에서 참조되는 경우.
  • new 키워드가 사용될 때 개체의 인스턴스입니다.
  • 화살표 기능을 사용할 때 객체`

  • 객체의 메서드 내에서 - 화살표 기능 없음


    ```javascript
    const obj = {
        name: "obj",
        printName() {
            console.log(this.name);
        },
        printObj() {
            console.log(this);
        }
    }
    obj.printName(); // obj
    obj.printObj(); // {name: "obj", printName: ƒ, printObj: ƒ}
    ```
    

    this 내에서 객체의 메서드 - 화살표 함수



    화살표 함수에서 this 값은 항상 부모가 아닌 화살표 함수에서 this 값입니다.
    ```javascript
    const obj = {
        name: "obj",
        printObj: () => {
            console.log(this); // this refers to the window
        }
    }
    obj.printObj() // Window {window: Window, self: Window, document: document, name: "", location: Location, …}
    ```
    

    이것은 함수 본문 내에서


    ```javascript
    function greet() {
        console.log(this);  
    }
    greet(); // Window {window: Window, self: Window, document: document, name: "", location: Location, …}
    ```
    

    이것은 new 키워드가 사용될 때


    ```javascript
    function Game(inTitle) {
        this.title = inTitle;
        console.log(this); // Game {title: "pong"}
    }
    
    const game = new Game("pong");
    ```
    

    이것은 객체 메소드의 콜백 내 - 화살표 기능 없음


    ```javascript
    const fruits = {
        name: "fruits",
        fruits: ["apple", "mango", "banana"],
        printFruits() {
            console.log(this); // {name: "fruits", fruits: Array(3), printFruits: ƒ}
            this.fruits.forEach(function(fruit) {
                console.log(this); // Window {window: Window, self: Window, document: document, name: "", location: Location, …} * 3 times
            })
        }
    }
    
    fruits.printFruits();
    ```
    

    객체의 메소드에서 콜백 내 this - 화살표 함수


    ```javascript
    const fruits = {
        name: "fruits",
        fruits: ["apple", "mango", "banana"],
        printFruits() {
            console.log(this); // {name: "fruits", fruits: Array(3), printFruits: ƒ}
            this.fruits.forEach((fruit) => {
                console.log(this); // {name: "fruits", fruits: Array(3), printFruits: ƒ} * 3 times
            })
        }
    }
    
    fruits.printFruits();
    ```
    

    좋은 웹페이지 즐겨찾기