JavaScript-this代名詞

什麼是 this?

this 是全域物件,在瀏覽器叫 window,在 node 叫 global。

this 說明

  1. 誰呼叫,誰就是 this , 沒有明確呼叫者 this 就是 window

    在 JavaScript 裡 this 寫在哪沒有關係,跟怎麼執行有關。

    const hero = {
      name: "kk",
      power: 100,
      attack: function () {
        console.log(this); //即使寫在這,也不知道是什麼
      },
    };
    hero.attack(); //{name:"kk",power:100,attack:[Function:attack]}
    //hero呼叫,所以this就是hero
    
    function hi() {
      console.log(this);
    }
    hi(); //沒有明確呼叫者,就是window
    
  2. 箭頭函示沒有自己的 this,this 等於 window,就算有明確的呼叫者
    const hero = {
      name: "kk",
      power: 100,
      attack: () => {
        console.log(this);
      },
    };
    hero.attack(); //箭頭函示->window
    
  3. 有沒有用 new,有用 new,this 就是{ }
    function hero(name, power) {
      this.name = name;
      this.power = power;
    }
    
    const h1 = hero("kk", 100); //沒有明確呼叫hero,this是window
    const h1 = new hero("kk", 100); //this是{ }
    
  4. 是否有使用 apply、call、bind,有的話 this 會轉向
     const hero = {power:100}
     function hi(){
         console.log(this)
     }
     hi.apply(hero)//{power:100},會把hero當this帶進來
     hi.call(hero)//{power:100},會把hero當this帶進來
     const new_hi = hi.bind(hero); //會回傳一個新的function,不會馬上執行
     new_hi()//{power:100}
     hi.bind(hero)(); //{power:100},後面加上()會馬上執行IIFE
    
     **apply與call差別**
     const hero = {power:100}
     function hi(msg){
         console.log(msg)
         console.log(this)
     }
     hi.apply(hero,[123])//123,逗號後是參數,apply參數要用陣列包
                             //{power:100}
     hi.call(hero,123)//123,逗號後是參數
                         //{power:100}
    
  5. 是否有使用嚴格模式"use strict",(可以放在檔案上面或是 function 裡面)
    "use strict";
    function hi() {
      console.log(this);
    }
    hi(); //undefined,不會是window
    
comments powered by Disqus