【问题标题】:typescript this as parameter打字稿 this 作为参数
【发布时间】:2017-08-13 06:50:43
【问题描述】:

当我浏览 rxjs 库时,我偶然发现了这个函数:

export function map<T, R>(this: Observable<T>, project: (value: T, index: number) => R, thisArg?: any): Observable<R> {
   if (typeof project !== 'function') {
     throw new TypeError('argument is not a function. Are you looking for `mapTo()`?');
   }
   return this.lift(new MapOperator(project, thisArg));
}

来源:https://github.com/ReactiveX/rxjs/blob/master/src/operator/map.ts

我想知道当传递一个名为 this 的参数时会发生什么。 它只是像任何其他参数一样被处理,还是在您执行此操作时会打字一些特殊动作?

【问题讨论】:

    标签: typescript rxjs5


    【解决方案1】:

    您不能直接传递map 与签名中的this 参数相对应的参数。 this 参数被 TypeScript 用来指示上下文的类型,在运行时没有对应的参数。

    不过,map 函数可以使用Function.prototype.callFunction.prototype.apply 调用,上下文可以传递给callapply

    例如:

    import { of } from "rxjs/observable/of";
    import { map } from "rxjs/operator/map";
    
    const source = of(1);
    const mapped = map.call(source, value => value + 1);
    

    在此示例中,source 将对应于 map 的实现中的 this,其类型为 Observable&lt;number&gt;

    有关详细信息,请参阅documentation 中的“this 参数”部分。

    【讨论】:

      猜你喜欢
      • 2019-09-20
      • 1970-01-01
      • 1970-01-01
      • 2022-11-11
      • 2023-01-17
      • 1970-01-01
      • 1970-01-01
      • 2020-10-25
      • 1970-01-01
      相关资源
      最近更新 更多