参见英文答案 >
How to access the correct `this` inside a callback?8个
我有一个简单的JSFiddle here演示了我的问题.
我有一个简单的JSFiddle here演示了我的问题.
var b = document.getElementById("b"); function A() { this.f = "1"; } A.prototype.t = function() { b.innerHTML = this.f; }; var a = new A(); var l = a.t; l();
当我尝试拨打a.t时,为什么这个未定义?如何在不过度冗长或存储太多的情况下恢复该上下文?@H_404_4@
解决方法
Why is this undefined when I try to call a.t?@H_404_4@
因为在JavaScript中,这主要是通过如何调用函数来设置的,而不是在它定义的位置. a.t()在调用中将其设置为a,但l()将此设置为undefined(在严格模式下)或全局对象(在松散模式下).@H_404_4@
> Mythical methods
> You must remember this
@H_404_4@
唯一的例外是“绑定”函数(与Function#bind一样)或ES6的“箭头”函数(从定义它们的上下文中获取它们).@H_404_4@
How do I recover that context without being overly verbose or storing too much?@H_404_4@
Function#bind
通常是一个很好的答案:@H_404_4@
var l = a.t.bind(a); l();
它返回一个新函数,在调用时,使用此set将原始函数调用到您给bind的第一个参数. (你也可以绑定其他参数.)这是一个ES5函数,但如果你需要支持真正的旧浏览器,你可以轻松地填充它.@H_404_4@
如果您只需要使用特定的值调用l,并且不总是使用该值,则可以使用函数#call或函数#apping来使用该值:Robert Rossmann points out@H_404_4@
l.call(this,'a','b','c'); // Calls `l` with `this` set to `a` and args 'a',and 'c' l.apply(this,['a','c']); // Calls `l` with `this` set to `a` and args 'a',and 'c' -- note they're specified in an array