一篇文章帶你了解JavaScript this關(guān)鍵字
與其他語言相比,this關(guān)鍵字在JavaScript中的行為略有不同。JavaScript中,this關(guān)鍵字引用其所屬的對象。根據(jù)使用位置,它具有不同的值。
一、前言
方法中,this關(guān)鍵字引用其所屬的對象。
this指的是全局對象在函數(shù)中。
this引用全局對象在函數(shù)中。
在嚴(yán)格模式下,this是未定義的在事件中。
this指的是接收事件的元素像call()和apply()這樣的方法,可以將其引用到任何對象。
二、方法上下文
在對象方法中,this指代方法的user。
當(dāng)調(diào)用user.getName()時,函數(shù)內(nèi)部將this綁定到user對象:
例:
- <!DOCTYPE html>
- <html>
- <title>項目</title>
- <body style="background-color: aqua;">
- <p>在此示例中,<b> user </b>對象是<b> getName </b>方法的所有者:</p>
- <script>
- // 創(chuàng)建一個對象
- var user = {
- firstName: "基礎(chǔ)教程",
- lastName: "baidu.com",
- age: 5,
- getName: function() {
- return this.firstName + " " + this.lastName;
- }
- };
- document.write(user.getName());
- </script>
- </body>
- </html>
這里user對象是所有者getName的方法。
1. 全局上下文
在全局執(zhí)行上下文中(在任何函數(shù)之外),this無論是否處于嚴(yán)格模式下,都引用全局對象。
示例
- <!DOCTYPE html>
- <html>
- <title>項目</title>
- <body style="background-color: aqua;">
- <p>在全局執(zhí)行上下文中(在任何函數(shù)之外),這指的是全局對象:</p>
- <p>訪問調(diào)試在您的瀏覽器按F12,并選擇"控制臺"在調(diào)試器菜單:</p>
- <script>
- //在Web瀏覽器中,窗口對象也是全局對象:
- console.log(this === window); // true
- a = 50;
- console.log(window.a); // 50
- this.b = "baidu.com";
- console.log(window.b) // "nhooo.com"
- console.log(b) // "nhooo.com"
- </script>
- </body>
- </html>
在瀏覽器窗口中,全局對象是[object Window]。
2. 函數(shù)上下文
在函數(shù)內(nèi)部,this值取決于函數(shù)的調(diào)用方式。由于以下代碼不在嚴(yán)格模式下,this因此默認(rèn)為全局對象,即瀏覽器中的[object Window]。
- function myFunc() {
- return this;
- }
在嚴(yán)格模式,然而this的值是undefined。
- function myFunc() {
- "use strict";
- return this;
- }
因此,在嚴(yán)格模式下,如果執(zhí)行上下文未定義它,則它將保持未定義狀態(tài)。
三、this在DOM事件處理程序中
當(dāng)一個函數(shù)用作事件處理程序時,this將被設(shè)置為觸發(fā)事件的元素:
示例
- let btn = document.querySelector("button");
- btn.onclick = function() {
- this.style.display = "none";
- };
從內(nèi)聯(lián)事件處理程序調(diào)用代碼時,會將this設(shè)置為放置監(jiān)聽器的元素:
- <button onclick="this.style.display='none'">點擊刪除我</button>
四、顯式函數(shù)綁定
call()和apply()方法是預(yù)定義的JavaScript方法。
它們都可以用于調(diào)用以另一個對象作為參數(shù)的對象方法。
- <script>
- function add(c, d) {
- return this.a + this.b + c + d;
- }
- var obj = {
- a: 5,
- b: 10
- };
- //第一個參數(shù)是用作
- //'this',后續(xù)參數(shù)作為
- //函數(shù)調(diào)用中的參數(shù)
- document.writeln(add.call(obj, 5, 7)); // 27
- //第一個參數(shù)是要使用的對象
- // 'this',第二個是一個數(shù)組
- //成員用作函數(shù)調(diào)用中的參數(shù)
- document.writeln(add.apply(obj, [10, 20])); // 45
- </script>
箭頭函數(shù)(=>)
在箭頭函數(shù)(=>)中,this始終指向它被創(chuàng)建時所處的詞法作用域中的this。全局代碼中,它將被設(shè)置為全局對象:
- <script>
- var globalObj = this;
- var myFunc = (() => this);
- document.write(myFunc() === globalObj);// true
- </script>
五、總結(jié)