How do I ensure that Javascript's “this” will refer to the object when using setTimeout?

空扰寡人 提交于 2019-12-13 02:48:32

问题


<!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>

And here is the console output:

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…}

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?

Thanks


回答1:


Use a .bind call.

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

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




回答2:


The answers using bind are the best, most modern way, of handling this. But if you have to support older environments and don't want to shim Function.prototype.bind, then you could also do it like this:

Obj.prototype.bar = function (){
    log('bar() was triggered');
    var ob = this;
    setTimeout(function() {ob.foo();}, 300);
}



回答3:


Use bind method like this

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


来源:https://stackoverflow.com/questions/20873596/how-do-i-ensure-that-javascripts-this-will-refer-to-the-object-when-using-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!