简体   繁体   中英

How do I ensure that Javascript's “this” will refer to the object when using 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>

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

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

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);
}

使用像这样的bind方法

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM