首页 > web前端 > js教程 > 正文

如何在Javascript的setTimeout回调中正确使用'this”关键字?

Barbara Streisand
发布: 2024-10-24 10:37:30
原创
392 人浏览过

How to Use

JavaScript 中的 setTimeout 和“this”

在 JavaScript 中使用 setTimeout 函数时,了解 this 关键字在 JavaScript 中的工作原理至关重要回调函数。在某些情况下,您可能会遇到错误,指出在超时延迟后引用的方法未定义。

请考虑以下代码:

<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学习者快速成长!