在使用setTimeout时,如何确保Javascript的"this"将引用该对象?

use*_*601 0 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>
Run Code Online (Sandbox Code Playgroud)

这是控制台输出:

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…}
Run Code Online (Sandbox Code Playgroud)

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

谢谢

Dan*_*ite 7

使用.bind电话.

setTimeout(this.foo.bind(this),300);
Run Code Online (Sandbox Code Playgroud)

并非所有的浏览器都支持它,但对MDN垫片,并强调有_.bind(...)以及