失去“这个”传递成员时JavaScript中的上下文 [英] Losing "this" context in JavaScript when passing around members

查看:88
本文介绍了失去“这个”传递成员时JavaScript中的上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的JSFiddle 这里来证明我的问题。

I have a simple JSFiddle here demonstrating my issue.

我有这个JavaScript代码:

I have this JavaScript code:

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();

为什么这个未定义当我尝试打电话给?如何在不过度冗长或存储过多的情况下恢复上下文?

Why is this undefined when I try to call a.t? How do I recover that context without being overly verbose or storing too much?

推荐答案


为什么这样我尝试打电话时未定义?

Why is this undefined when I try to call a.t?

因为在JavaScript中,这个是主要由如何调用函数设置,而不是在其定义的位置。 at()在通话中将设置为 a l()设置为 undefined (in严格模式)或全局对象(在松散模式下)。

Because in JavaScript, this is set primarily by how the function is called, not where it's defined. a.t() sets this to a within the call, but l() sets this either to undefined (in strict mode) or the global object (in loose mode).

更多(在我的博客上)

唯一的例外是绑定函数(与函数#bind 一样)或ES6的箭头函数(从上下文获取 this 它们被定义了。

The only exceptions are "bound" functions (as with Function#bind) or ES6's "arrow" functions (which get their this from the context in which they're defined).


如何在不过度冗长或存储太多的情况下恢复上下文?

How do I recover that context without being overly verbose or storing too much?

函数#bind 通常是一个很好的答案:

Function#bind is usually a good answer:

var l = a.t.bind(a);
l();

它返回一个新函数,在调用时,用调用原始函数设置为您给出的第一个参数 bind 。 (你也可以绑定其他参数。)这是一个ES5函数,但如果你需要支持真正的旧浏览器,你可以轻松地将它填充。

It returns a new function that, when called, calls the original with this set to the first argument you gave bind. (You can also bind other arguments.) It's an ES5 function, but if you need to support really old browsers, you can easily polyfill it.

如果您只需要致电 l 并使用特定的值,并不总是使用该值,因为 Robert Rossmann指出您可以使用功能#call 功能#application

If you just need to call l with a specific this value, and not always have it use that value, as Robert Rossmann points out you can use Function#call or Function#apply:

l.call(this, 'a', 'b', 'c');    // Calls `l` with `this` set to `a` and args 'a', 'b', and 'c'
l.apply(this, ['a', 'b', 'c']); // Calls `l` with `this` set to `a` and args 'a', 'b', and 'c' -- note they're specified in an array

这篇关于失去“这个”传递成员时JavaScript中的上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆