为什么我们需要“var self = this"?在 Javascript 类中? [英] Why do we need "var self = this" in classes in Javascript?
问题描述
为什么我们不能在下面的例子中直接使用this
而不是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.
推荐答案
没有理由为什么你不能直接在那里使用 this
(我会说它会如果你做了,那么可读性会更好).
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).
然而,var self = this;
通常在以下情况下需要(基本上,任何异步操作,如事件绑定、AJAX 处理程序等,其中 this代码>被推迟直到它等于其他东西);
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屋!