搜尋
首頁web前端前端問答javascriptthis什麼意思

javascriptthis什麼意思

Jun 30, 2021 pm 02:38 PM
javascriptthis

this的中文意思是“當前;這個”,是javascript中的一個指標型變量,它指向當前函數的運行環境。在不同的場景中呼叫同一個函數,this的指向會發生變化,但它永遠指向其所在函數的真實呼叫者;如果沒有呼叫者,this就指向window。

javascriptthis什麼意思

本教學操作環境:windows7系統、javascript1.8.5版、Dell G3電腦。

JavaScript 函數的作用域是靜態的,但是函數的呼叫卻是動態的。由於函數可以在不同的運行環境內執行,因此 JavaScript 在函數體內定義了 this 關鍵字,用來取得目前的運行環境。

this 是一個指標型變量,它指向目前函數的運行環境。

在不同的場景中呼叫同一個函數,this的指向也可能會發生變化,但是它永遠指向其所在函數的真實呼叫者(誰呼叫就指向誰);如果沒有呼叫者,this就指向全域物件window。

使用 this

this 是由 JavaScript 引擎在執行函數時自動產生的,存在於函數內的動態指針,指涉目前呼叫物件。具體用法如下:

this[.属性]

如果 this 未包含屬性,則傳遞的是目前物件。

this 用法靈活,其包含的值也是變化多端。例如,下面範例使用 call() 方法不斷改變函數內 this 指涉物件。

var x = "window";  //定义全局变量x,初始化字符串为“window”
function a () {  //定义构造函数a
    this.x = "a";  //定义私有属性x,初始化字符a
}
function b () {  //定义构造函数b
    this.x = "b";  //定义私有属性x,初始化为字符b
}
function c () {  //定义普通函数,提示变量x的值
    console.log(x);
}
function f () {  //定义普通函数,提示this包含的x的值
    console.log(this.x);
}
f();  //返回字符串“window”,this指向window对象
f.call(window);  //返回字符串“window”,指向window对象
f.call(new a());  //返回字符a,this指向函数a的实例
f.call(new b());  //返回字符b,this指向函数b的实例
f.call(c);  //返回undefined,this指向函数c对象

以下簡單總結 this 在 5 個常用場景中的表現以及應對策略。

1. 普通呼叫

下面範例示範了函數參考和函數呼叫對 this 的影響。

var obj = {  //父对象
    name : "父对象obj",
    func : function () {
        return this;
    }
}
obj.sub_obj = {  //子对象
    name : "子对象sub_obj",
    func : obj.func
}
var who = obj.sub_obj.func();
console.log(who.name);  //返回“子对象sub_obj”,说明this代表sub_obj

如果把子物件 sub_obj 的 func 改為函數呼叫。

obj.sub_obj = {
    name : "子对象sub_obj",
    func : obj.func()  //调用父对象obj的方法func
}

則函數中的 this 所代表的是定義函數時所在的父物件 obj。

var who = obj.sub_obj.func;
console.log(who.name);  //返回“父对象obj”,说明this代表父对象obj

2. 實例化

使用 new 指令呼叫函數時,this 總是指涉實例物件。

var obj = {};
obj.func = function () {
    if (this == obj) console.log("this = obj");
    else if (this == window) console.log("this = window");
    else if (this.contructor == arguments.callee) console.log("this = 实例对象");
}
new obj.func;  //实例化

3. 動態呼叫

使用 call 和 apply 可以強制改變 this,使其指向參數物件。

function func () {
    //如果this的构造函数等于当前函数,则表示this为实例对象
    if (this.contructor == arguments.callee) console.log("this = 实例对象");
    //如果this等于window,则表示this为window对象
    else if (this == window) console.log("this = window对象");
    //如果this为其他对象,则表示this为其他对象
    else console.log("this == 其他对象 \n this.constructor =" + this.constructor);
}
func();  //this指向window对象
new func();  //this指向实例对象
cunc.call(1);  //this指向数值对象

在上面範例中,直接呼叫 func() 時,this 代表 window 物件。當使用 new 指令呼叫函數時,將會建立一個新的實例對象,this 就指向這個新建立的實例物件。

使用call() 方法執行函數func() 時,由於call() 方法的參數值為數字1,則JavaScript 引擎會將數字1 強制封裝為數值對象,此時this 就會指向這個數值物件。

4. 事件處理

在事件處理函數匯總,this 總是指向觸發該事件的物件。

<input type="button" value="测试按钮" />
<script>
    var button = document.getElementsByTagName("put")[0];
    var obj = {};
    obj.func = function () {
        if (this == obj) console.log("this = obj");
        if (this == window) console.log("this = window");
        if (this == button) console.log("this = button");
    }
    button.onclick = obj.func;
</script>

在上面程式碼中,func() 所包含的this 不再指向物件obj,而是指向按鈕button,因為func() 是被傳遞給按鈕的事件處理函數之後才被呼叫執行的。

如果使用DOM2 等級標準註冊事件處理函數,程式如下:

if (window.attachEvent) {  //兼容IE模型
    button.attachEvent("onclick", obj.func);
} else {  //兼容DOM标准模型
    button.addEventListener("click", obj.func, true);
}

在IE 瀏覽器中,this 指向window 物件和button 對象,而在DOM 標準的瀏覽器中僅指向button 對象。因為,在 IE 瀏覽器中,attachEvent() 是 window 物件的方法,當呼叫該方法時,this 會指向 window 物件。

為了解決瀏覽器相容性問題,可以呼叫 call() 或 apply() 方法強制在物件 obj 身上執行方法 func(),避免出現不同的瀏覽器對 this 解析不同的問題。

if (window.attachEvent) {
    button.attachEvent("onclick", function () {  //用闭包封装call()方法强制执行func()
        obj.func.call(obj);
    });
} else {
    button.attachEventListener("onclick", function () {
        obj.func.call(obj);
    }, true);
}

當再次執行時,func() 中包含的 this 總是指向物件 obj。

5. 定時器

使用定時器呼叫函數。

var obj = {};
obj.func = function () {
    if (this == obj) console.log("this = obj");
    else if (this == window) console.log("this = window对象");
    else if (this.constructor == arguments.callee) console.log("this = 实例对象");
    else console.log("this == 其他对象 \n this.constructor =" + this.constructor);
}
setTimeOut(obj.func, 100);

在 IE 中 this 指向 window 物件和 button 對象,具體原因與上面講解的 attachEvent() 方法相同。在符合 DOM 標準的瀏覽器中,this 指向 window 對象,而不是 button 物件。

因為方法 setTimeOut() 是在全域作用域中被執行的,所以 this 指向 window 物件。若要解決瀏覽器相容性問題,可以使用 call 或 apply 方法來實作。

setTimeOut (function () {
    obj.func.call(obj);
}, 100);

【相關推薦:javascript學習教學

#

以上是javascriptthis什麼意思的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
反應的局限性是什麼?反應的局限性是什麼?May 02, 2025 am 12:26 AM

Include:1)AsteeplearningCurvedUetoItsVasteCosystem,2)SeochallengesWithClient-SiderEndering,3)潛在的PersperformanceissuesInsuesInlArgeApplications,4)ComplexStateStateManagementAsappsgrow和5)TheneedtokeEedtokeEedtokeEppwithitsrapideDrapidevoltolution.thereedtokeEppectortorservolution.thereedthersrapidevolution.ththesefactorsshesssheou

React的學習曲線:新開發人員的挑戰React的學習曲線:新開發人員的挑戰May 02, 2025 am 12:24 AM

reactischallengingforbeginnersduetoitssteplearningcurveandparadigmshifttocoment oparchitecent.1)startwithofficialdocumentationforasolidFoundation.2)了解jsxandhowtoembedjavascriptwithinit.3)

為React中的動態列表生成穩定且獨特的鍵為React中的動態列表生成穩定且獨特的鍵May 02, 2025 am 12:22 AM

ThecorechallengeingeneratingstableanduniquekeysfordynamiclistsinReactisensuringconsistentidentifiersacrossre-rendersforefficientDOMupdates.1)Usenaturalkeyswhenpossible,astheyarereliableifuniqueandstable.2)Generatesynthetickeysbasedonmultipleattribute

JavaScript疲勞:與React及其工具保持最新JavaScript疲勞:與React及其工具保持最新May 02, 2025 am 12:19 AM

javascriptfatigueinrectismanagbaiblewithstrategiesLike just just in-timelearninganning and CuratedInformationsources.1)學習whatyouneedwhenyouneedit

使用USESTATE()掛鉤的測試組件使用USESTATE()掛鉤的測試組件May 02, 2025 am 12:13 AM

tateractComponents通過theusestatehook,使用jestandReaCtTestingLibraryToSigulationsimintionsandIntractions and verifyStateChangesInTheUI.1)underthecomponentAndComponentAndComponentAndConconentAndCheckInitialState.2)模擬useruseruserusertactionslikeclicksorformsorformsormissions.3)

React中的鑰匙:深入研究性能優化技術React中的鑰匙:深入研究性能優化技術May 01, 2025 am 12:25 AM

KeysinreactarecrucialforopTimizingPerformanceByingIneFefitedListupDates.1)useKeyStoIndentifyAndTrackListelements.2)避免使用ArrayIndi​​cesasKeystopreventperformansissues.3)ChooSestableIdentifierslikeIdentifierSlikeItem.idtomaintainAinainCommaintOnconMaintOmentStateAteanDimpperperFermerfermperfermerformperfermerformfermerformfermerformfermerment.ChosestopReventPerformissues.3)

反應中的鍵是什麼?反應中的鍵是什麼?May 01, 2025 am 12:25 AM

ReactKeySareUniqueIdentifiers usedwhenrenderingListstoimprovereConciliation效率。 1)heelPreactrackChangesInListItems,2)使用StableanDuniqueIdentifiersLikeItifiersLikeItemidSisRecumended,3)避免使用ArrayIndi​​cesaskeyindicesaskeystopreventopReventOpReventSissUseSuseSuseWithReRefers和4)

反應中獨特鍵的重要性:避免常見的陷阱反應中獨特鍵的重要性:避免常見的陷阱May 01, 2025 am 12:19 AM

獨特的keysarecrucialinreactforoptimizingRendering和MaintainingComponentStateTegrity.1)useanaturalAlaluniqueIdentifierFromyourDataiFabable.2)ifnonaturalalientedifierexistsistsists,generateauniqueKeyniqueKeyKeyLiquekeyperaliqeyAliqueLiqueAlighatiSaliqueLiberaryLlikikeuuId.3)deversearrayIndi​​ceSaskeyseSecialIndiceSeasseAsialIndiceAseAsialIndiceAsiall

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具