# This 指向 ###### tags: `單元筆記` `javascript` `觀念` ## 介紹 ## 範例 ```javascript= <script> // this 代表函式的綁定物件,通常使用於函式內 // 在不同的地方,綁定物件也就是 this 會不同 // 情況一 : 獨立的函式 function t1() { console.log("t1 的 this : ", this); // 指向 window 物件 console.log("視窗寬度 : ", this.innerWidth); // 視窗寬度 } t1(); // 情況二 : 物件的方法 let obj = { x: 10, t2: function () { console.log("t2 的 this : ", this); // 就是方法所屬的整個物件本人 console.log("物件內的屬性 : ", this.x); // 印出物件屬性 }, }; obj.t2(); // 情況三 : 事件處理的函式 document.addEventListener("click", function () { console.log("事件的 this : ", this); // 指的就是觸發這個事件的對象物件 是誰做了事件監聽?就是誰 this.body.append("Click !!!"); // 做甚麼事? }); // 情況四 : 建構函式 function t3() { console.log("t3 的 this : ", this); // 這邊瀏覽器就會幫我們建立一個空白物件 this.x = 1994; // 幫空物件添加屬性 this.y = "Allen"; } // new t3(); let r3 = new t3(); console.log(r3); // 進階 : 自訂綁定物件 let obj2 = { x: 1994, y: "Amy", }; // 重新綁定 bind function t4() { console.log("t4 的 this : ", this); // 指向 window 物件 } t4(); let r4 = t4.bind(obj2); r4(); let r4_2 = t4.bind(document); r4_2(); // 用 apply 呼叫函式 自己設定綁定物件及用陣列傳入參數 function t5(a, b) { console.log("結果 : ", a + b); console.log("t5 的 this : ", this); } t5(8, 9); t5.apply(obj, [4, 7]); // 用 call 呼叫函式 與apply相同只差在不用陣列傳入 t5.call(obj2, 7, 23); </script> ``` ## 說明 ## 小記 :::info ::: ## 參考 [xxx](xxx) [一次搞懂前端面試最愛問的 apply、bind、call](https://medium.com/schaoss-blog/%E4%B8%80%E6%AC%A1%E6%90%9E%E6%87%82%E5%89%8D%E7%AB%AF%E9%9D%A2%E8%A9%A6%E6%9C%80%E6%84%9B%E5%95%8F%E7%9A%84-apply-bind-call-708f57518776)