【发布时间】:2014-01-19 08:22:27
【问题描述】:
<!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。如何防止这种行为或正确处理这种行为?
谢谢
【问题讨论】:
-
@Popnoodles 这不是为我做的。工作和以前一样。 Bind 是我需要的答案,但谢谢。
标签: javascript this settimeout