javascript - 奇怪的 javascript 语法返回 {unsubscribe() {}};
问题描述
我在angular tutorial中发现了奇怪的结构。退货部分发生了什么?代码块内的函数调用后跟空对象?
// This function runs when subscribe() is called
function sequenceSubscriber(observer) {
// synchronously deliver 1, 2, and 3, then complete
observer.next(1);
observer.next(2);
observer.next(3);
observer.complete();
// unsubscribe function doesn't need to do anything in this
// because values are delivered synchronously
return {unsubscribe() {}};
}
// Create a new Observable that will deliver the above sequence
const sequence = new Observable(sequenceSubscriber);
// execute the Observable and print the result of each notification
sequence.subscribe({
next(num) { console.log(num); },
complete() { console.log('Finished sequence'); }
});
// Logs:
// 1
// 2
// 3
// Finished sequence
解决方案
您说代码return {unsubscribe() {}};
是“代码块内的函数调用,后跟空对象”;这是不正确的。
实际发生的是函数 ,sequenceSubscriber
正在返回一个Object
带有名为“取消订阅”的函数作为属性的函数。该功能什么也不做。这是利用您可以在此处看到的新功能简写:方法定义
考虑代码:
const foo = {
bar(){}
};
创建一个foo
具有function
,的 Object bar
,它什么也不做。
这样做的原因是为了履行 Rx 定义的接口契约Observables
以及tc39/proposal-observableSubscription
中定义的接口:
interface Subscription {
// Cancels the subscription
unsubscribe() : void;
// A boolean value indicating whether the subscription is closed
get closed() : Boolean;
}
推荐阅读
- postgresql - Postgresql 唯一安装 id
- css - Shiny:textInputs 和 selectInputs 的不同样式
- android - 将图像从一个文件夹复制到另一个文件夹 - Android
- python - Python regex cut pattern string
- java - Java调用泛型类型的静态方法
- java-8 - websphere 8.5 中的axis2.jar
- python - Python中文件夹何时为空时通知?
- laravel - Laravel 唯一请求更新
- android - 根据条件隐藏 Listview 行中的 textview
- python - Python Pandas 查找数据框中存在的多个列标题