<!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。如何防止该行为或正确使用该行为?
由于
答案 0 :(得分:6)
使用.bind
来电。
setTimeout(this.foo.bind(this),300);
并非所有浏览器都支持它,但MDN上有垫片,而Underscore也有_.bind(...)
答案 1 :(得分:3)
使用bind
的答案是处理此问题的最佳,最现代的方法。但是,如果您必须支持较旧的环境并且不想填充Function.prototype.bind
,那么您也可以这样做:
Obj.prototype.bar = function (){
log('bar() was triggered');
var ob = this;
setTimeout(function() {ob.foo();}, 300);
}
答案 2 :(得分:0)
使用像这样的绑定方法
setTimeout(this.foo.bind(this),300);