奇怪的javascript语法return {unsubscribe(){}};

时间:2018-07-18 18:53:46

标签: javascript angular

我在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

2 个答案:

答案 0 :(得分:1)

您说代码return {unsubscribe() {}};是“代码块内的函数调用,后跟空对象”;那是不正确的。

实际上发生的是,函数sequenceSubscriber返回的Object带有一个名为“ unsubscribe”的函数作为属性。该功能不执行任何操作。这是利用新功能的简写,您可以在这里看到:Method definitions

考虑代码:

const foo = {
    bar(){}
};

创建一个对象foo,它有一个functionbar,什么也没做。

为什么这样做的原因是为了满足Rx为Observables定义的接口协定以及tc39/proposal-observable中定义的Subscription接口:

interface Subscription {

    // Cancels the subscription
    unsubscribe() : void;

    // A boolean value indicating whether the subscription is closed
    get closed() : Boolean;
}

答案 1 :(得分:0)

该函数返回一个对象,该对象包含不执行任何操作的unsubscribe函数。正如评论所述,unsubscribe功能是不需要的,因为观察者是同步发出的。