<!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 的所有权。我如何防止这种行为或正确处理这种行为?
谢谢
最佳答案
使用 .bind
调用。
setTimeout(this.foo.bind(this),300);
并非所有浏览器都支持它,但 MDN 上有一个垫片,Underscore 也有 _.bind(...)
关于javascript - 如何确保使用 setTimeout 时 Javascript 的 "this"会引用该对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20873596/