[英]Accessing its own object properties before function returns
In the below code, the anonymous function run by the forEach
loop is able to call subscription.dispose()
on its first run-through, before the buttonClicks.forEach(..)
has returned the subscription object to the subscription
variable.在下面的代码中,由
forEach
循环运行的匿名函数能够在第一次运行时调用subscription.dispose()
,然后buttonClicks.forEach(..)
将订阅对象返回给subscription
变量。
How can forEach(..)
have access to an object it returns, before forEach
has finished running at least once?在
forEach
至少运行一次之前, forEach(..)
如何访问它返回的对象?
function(button) {
var buttonClicks = Observable.fromEvent(button, "click");
// In the case of an Observable, forEach returns a subscription object.
var subscription =
buttonClicks.
forEach(function(clickEvent) {
alert("Button was clicked. Stopping Traversal.");
// Stop traversing the button clicks
subscription.dispose();
});
}
The variable subscription
is already declared.变量
subscription
已经声明。
It will be initialized after forEach
returns, before that, it is undefined
.它将在
forEach
返回后初始化,在此之前,它是undefined
。
So the click handler can refer to the variable.所以点击处理程序可以引用该变量。 What it cannot do is actually call
dispose
, for that it needs that variable to hold a value (but this won't happen until someone clicks, and by then the forEach
has long returned and the variable assigned).它不能做的实际上是调用
dispose
,因为它需要该变量来保存一个值(但这不会发生,直到有人点击,然后forEach
早已返回并分配了变量)。
Note that Observable#forEach
does not immediately run the function you pass it (unlike, say, Array#forEach
).请注意,
Observable#forEach
不会立即运行您传递给它的函数(与Array#forEach
)。 The function is run every time the observable emits a value (here: a click has happened).每次 observable 发出值时都会运行该函数(此处:发生了单击)。
Also note that you could later assign subscription
to something else, and it will call dispose
on that.另请注意,您可以稍后将
subscription
分配给其他内容,它会调用dispose
。 It is not really tied to the object returned by forEach
.它并没有真正绑定到
forEach
返回的对象。 The click handler will continue to refer to the variable , not to the value of the variable at the time it was created.单击处理程序将继续参考变量,而不是在其创建时间变量的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.