别再拿着“这个”了在临时变量中
我必须不断地将 this
保存在临时变量中,以便在其他函数中访问它。例如,在下面的两种方法中,我将 this
保存在 that
变量中:
startTimer: function () {
var that = this;
if ($('#defaultCountdown:hidden'))
$('#defaultCountdown').show('slow');
shortly = new Date();
shortly.setSeconds(shortly.getSeconds() + 5);
$('#defaultCountdown').countdown('change', { until: shortly,
layout: '<ul id="errorList"><li>Next update in <b>{snn}</b> {desc}</li></ul>',
description: 'seconds',
onExpiry: function () {
that.performUpdate();
}
});
},
performUpdate: function () {
var that = this;
this.message.fetch({
success: function () {
$('#calleesStatuses').html('');
that.callees.refresh(that.message.get("Callees"));
$('#defaultCountdown').hide('slow');
that.startTimer();
},
error: function (request, settings) {
that.killCountDown();
showErrorMessage(request.responseText)
}
});
},
是否有解决此问题的方法,或者我可以使用 apply
吗?
I am continually having to hold this
in a temp variable in order to access it in other functions. For example in the two methods below, I am holding this
in a that
variable:
startTimer: function () {
var that = this;
if ($('#defaultCountdown:hidden'))
$('#defaultCountdown').show('slow');
shortly = new Date();
shortly.setSeconds(shortly.getSeconds() + 5);
$('#defaultCountdown').countdown('change', { until: shortly,
layout: '<ul id="errorList"><li>Next update in <b>{snn}</b> {desc}</li></ul>',
description: 'seconds',
onExpiry: function () {
that.performUpdate();
}
});
},
performUpdate: function () {
var that = this;
this.message.fetch({
success: function () {
$('#calleesStatuses').html('');
that.callees.refresh(that.message.get("Callees"));
$('#defaultCountdown').hide('slow');
that.startTimer();
},
error: function (request, settings) {
that.killCountDown();
showErrorMessage(request.responseText)
}
});
},
Is there anyway around this or could I possibly use apply
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
ECMAScript 5 引入了
Function.bind()
[docs],因此仅较新的浏览器支持它。可以在我链接到的文档中找到替代实现。如果您将其包含在代码中,则也可以在其他(较旧的)浏览器中使用bind()
。它允许您设置
this
应在函数中引用的对象。所以你可以写:ECMAScript 5 introduced
Function.bind()
[docs], so it is only supported by newer browsers. An alternative implementation can be found in the documentation I linked to. If you include it in your code, you can usebind()
in the other (older) browsers too.It lets you set the object
this
should refer to in the function. So you could write:我认为这是最简单的方法。这就是我所做的(尽管我正在编写 GWT 代码),在内部匿名函数中引用包装函数的
this
。即使像
this.wrappingMethod.this
这样的东西是可能的,将this
存储在根据您的喜好命名的变量中也更具可读性(您可以使用当然,更具描述性的名称),并且(仍然假设您冷以某种方式引用包装范围)它将更加健壮,因为您可以引入另一个级别而不必重写所有引用。I think that's the simplest way to do it. This is what I do (although I'm writing GWT code), to reference the
this
of the wrapping function in an inner anonymous function.Even if something like
this.wrappingMethod.this
were/are possible, storing the thethis
in a variable named according to your taste is a lot more readable (you could use a more descriptive name, ofcourse), and (still assuming you cold somehow reference the wrapping scope) it will be more robust since you could introduce another level without having to rewrite all the references.不,没有。闭包中的this
值与闭包定义的范围内的值不同,因此这是使其更清晰的唯一方法是在对象级别上定义它,因此至少每个对象只需执行一次,看起来您已经在这样做了。编辑:
删除“不,没有”,因为
bind
是一个有效的替代方案,并且有可比性实现(请参阅其他答案)。虽然我个人认为 var self = this; 更干净,您只需要为每个对象定义一次,但此时这是一个偏好问题。No, there isn't.The value ofthis
will be different in the closure than it is in the scope that the closure is defined so the only way to make it cleaner is to define it on an object level so at least you only have to do it once per object, which it looks like you are already doing anyway.Edit:
Strike out the "No there isn't" because
bind
is a valid alternative and there are comparability implementation (see other answer). Although I personally thinkvar self = this;
is cleaner and you only need to define it once per object but it is a matter of preference at this point.我想这并不舒服,但如果原始
this
是您可以执行诸如startTimer
和killCountdown
之类的函数的唯一上下文,那么事实并非如此。我建议给它一个更有意义的名称,例如计时器或其他名称。实际上,this
只是一个方便的关键字,用于引用我们正在执行的任何内容的所有者,并且它应该随着所有者的更改而更改。如果“this/that”变得难以阅读,解决方案是将名称从that
更改为语义上更有意义的名称。I guess it's no comfort, but not really if the original
this
is the only context in which you can execute functions likestartTimer
andkillCountdown
. What I'd recommend is giving it a more meaningful name, liketimer
or something. Really,this
is just a convenient keyword for referring to the owner of whatever we're executing, and it should change as the owner changes. If "this/that" is becoming hard to read, the solution is to change the name fromthat
to something more semantically meaningful.您正在做的是 JavaScript 中的标准模式,只不过传统上使用
self
而不是that
。但是您可以像这样使用bind()
方法:如果您使用的框架扩展了
Function
的原型以包含它,或者您的 Javascript 解释器是最新的足够的。 (bind
在幕后创建相同类型的匿名函数,但可以说效率较低,因为它必须处理各种特殊情况)。What you're doing is a standard pattern in JavaScript, except that it's traditional to use
self
instead ofthat
. But you can use thebind()
method like this:if you're working with a framework that extends the prototype of
Function
to include it, or your Javascript interpreter is recent enough. (bind
creates the same sort of anonymous function behind the scenes, but is arguably less efficient since it has to deal with all sorts of special cases).