首頁 > web前端 > js教程 > 主體

如何在Javascript的setTimeout回呼中正確使用「this」關鍵字?

Barbara Streisand
發布: 2024-10-24 10:37:30
原創
392 人瀏覽過

How to Use

JavaScript 中的setTimeout 和「this」

在JavaScript 中使用setTimeout 函數時,了解this 關鍵字在JavaScriptScript 中的工作原理至關重要回調函數。在某些情況下,您可能會遇到錯誤,指出在逾時延遲後引用的方法未定義。

請考慮以下程式碼:

<code class="javascript">test.prototype.method = function() {
    // method2 returns image based on the id passed
    this.method2('useSomeElement').src = "http://www.some.url";
    timeDelay = window.setTimeout(this.method, 5000);
};

test.prototype.method2 = function(name) {
    for (var i = 0; i < document.images.length; i++) {
        if (document.images[i].id.indexOf(name) > 1) {
            return document.images[i];
        }
    }
};</code>
登入後複製

在此範例中,呼叫了方法函數逾時時間為 5000 毫秒。但是,超時後,在回調函數中將無法再存取 method2 函數。這是因為 this 關鍵字引用的是全域對象,而不是測試原型的實例。

要解決此問題,您可以在呼叫 setTimeout 之前將 this 關鍵字綁定到回呼函數。這可以透過使用 .bind(this) 方法來實現:

<code class="javascript">test.prototype.method = function() {
    // method2 returns image based on the id passed
    this.method2('useSomeElement').src = "http://www.some.url";
    timeDelay = window.setTimeout(this.method.bind(this), 5000);
};</code>
登入後複製

透過將 this 關鍵字綁定到回調函數,您可以確保 method2 函數即使在超時後仍然可以存取。

以上是如何在Javascript的setTimeout回呼中正確使用「this」關鍵字?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!