首页 > 解决方案 > 奇怪的 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

标签: javascriptangular

解决方案


您说代码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;
}

推荐阅读