为什么我们需要“var self = this”在Javascript中的类? [英] Why do we need "var self = this" in classes in Javascript?
问题描述
为什么我们不能在以下示例中直接使用此
而不是 self
?
Why can't we directly use this
instead of self
in the following example?
function SeatReservation(name, initialMeal) {
var self = this;
self.name = name;
self.meal = ko.observable(initialMeal);
}
回复后,我了解到:
是的,没有必要在课堂上没有上下文切换。
Yes, there is no need if there is no context switch in class.
但是我会用这种方法作为约定,尽管有没必要。
But I will use this approach as "convention" although there is no need.
推荐答案
有没有的原因你不能使用这个
直接在那里(如果你做,我会说它的可读性会更好。)
There's no reason why you can't use this
directly there (and I would say it would be better for readability if you did).
然而,<$> c $ c> var self = this; 在以下情况下经常需要(基本上,任何异步动作,如事件绑定,AJAX处理程序等,其中的分辨率
延迟直到等于其他东西);
However, the var self = this;
is often needed in situations like the following (basically, any asynchronous action like event binding, AJAX handlers etc, where the resolution of this
is deferred until it equals something else);
function SeatReservation(name, initialMeal) {
var self = this;
self.name = name;
self.meal = ko.observable(initialMeal);
setTimeout(function () {
alert(self.name); // otherwise, this is window; use self to keep a reference to the "SeatReservation" instance.
}, 100);
}
这篇关于为什么我们需要“var self = this”在Javascript中的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!