我如何确保 Javascript 的“this"使用 setTimeout 时会引用对象吗? [英] How do I ensure that Javascript's "this" will refer to the object when using setTimeout?

查看:32
本文介绍了我如何确保 Javascript 的“this"使用 setTimeout 时会引用对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<!doctype html>
<html>
<head>
<title>What is 'this'?</title>
<script>
function Obj(){
    log('Obj instantiated');
}
Obj.prototype.foo = function (){
    log('foo() says:');
    log(this);
}
Obj.prototype.bar = function (){
    log('bar() was triggered');
    setTimeout(this.foo,300);
}
function log(v){console.log(v)}
var obj = new Obj();
</script>
</head>
<body>
    <button onclick="obj.foo()">Foo</button>
    <button onclick="obj.bar()">Bar</button>
</body>
</html>

这是控制台输出:

Obj instantiated
foo() says:
Obj {foo: function, bar: function}
bar() was triggered
foo() says:
Window {top: Window, window: Window, location: Location, external: Object, chrome: Object…}

因此,当它从 setTimeout 调用 obj.foo 时,'this' 会将所有权更改为 Window.我如何防止这种行为或正确处理这种行为?

So when it calls obj.foo from the setTimeout, 'this' changes ownership to the Window. How do I prevent that or properly work with that behavior?

谢谢

推荐答案

使用 .bind 调用.

setTimeout(this.foo.bind(this),300);

并非所有浏览器都支持它,但 MDN 上有一个 shim 并且 Underscore 也有 _.bind(...)

Not all browsers support it, but there is a shim on MDN and Underscore has _.bind(...) as well

这篇关于我如何确保 Javascript 的“this"使用 setTimeout 时会引用对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆