簡體   English   中英

Typescript — 無法理解 typescript -> return this._subscribe({onNext: onNext});

[英]Typescript — Unable to understand in typescript -> return this._subscribe({onNext: onNext});

閱讀一篇關於 observable 的文章,在問題末尾找到了代碼。

我無法理解以下幾行 ->

return this._subscribe({
                onNext: onNext,
                onError: onError || (() => {}),
                onCompleted: onCompleted || (() => {})
            });

1)我以前從未見過這種語法,這到底是什么?

使用 typeof 它說它是object ,但在我看來,它就像 function 中的 object 一樣,這沒有意義。

2)由於我看不懂代碼,所以玩了一下發現如果我返回

return {
                onNext: onNext,
                onError: onError || (() => {}),
                onCompleted: onCompleted || (() => {})
            }

代碼不會到達第二點(在“return new Observable((obs)”之后查找 -> // PointTwo 下面))

我假設第二個問題的答案將與第一個有關。

export class Observable<T> {
    /** Internal implementation detail */
    private _subscribe: any;

    /**
      * @constructor
      * @param {Function} subscribe is the function that is called when the 
      * observable is subscribed to. This function is given a subscriber/observer
      * which provides the three methods on the Observer interface:
      * onNext, onError, and onCompleted
    */
    constructor(subscribe: any) {
        if (subscribe) {
            this._subscribe = subscribe;
        };

    }


    // public api for registering an observer
    subscribe(onNext: any, onError?: any, onCompleted?: any) {
        if (typeof onNext === 'function') {
            return this._subscribe({
                onNext: onNext,
                onError: onError || (() => {}),
                onCompleted: onCompleted || (() => {})
            });
        } else {
          throw new Error("Please provide a function")
        }
    }

    static of(...args): Observable {
        return new Observable((obs) => {

       //pointTwo

            args.forEach(val => {
              console.log("3") 
              obs.onNext(val)
              });
            obs.onCompleted();

            return {
                unsubscribe: () => {
                    // just make sure none of the original subscriber's methods are never called.
                    obs = {
                        onNext: () => {},
                        onError: () => {},
                        onCompleted: () => {}
                    };
                }
            };
        });
    }
 }


 Observable.of(42).subscribe((num) => {console.log("number is -> " + num)})

這不是 TS 特定的。 他們所做的只是在 function 調用中直接定義 object 文字,而不是在調用 function 之前:

 const functionThatTakesAnObject = (obj) => { console.log(obj); }; const object = { prop1: true, somethingElse: '1' }; // pass in an object bound to a variable functionThatTakesAnObject(object); // define an object literal directly in the invocation functionThatTakesAnObject({ prop1: true, somethingElse: '1' });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM