<!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.如何防止该行为或正确使用该行为?
谢谢