在rxjs,
export function map<T, R, A>(project: (this: A, value: T, index: number) => R, thisArg: A): OperatorFunction<T, R>;
我找不到
thisArg: A
的用法。
这与
Array.prototype.map
中的目的相同:当您将函数作为参数传递时,上下文会丢失。
class Value {
constructor (public value:number) {}
addValue (x:number) { return this.value + x; }
}
const five = new Value(5);
[1, 2, 3].map(five.addValue); // Error because this is undefined
[1, 2, 3].map(five.addValue, five); // [6, 7, 8]
RxJS 示例
const source = Rx.Observable.from([1, 2, 3]);
source.map(five.addValue); // NaN...NaN...NaN
source.map(five.addValue, five); // 6...7...8
感谢 Geoffrey 的提醒,这是它的 rxjs 版本
import { of } from 'rxjs';
import { map } from 'rxjs/operators';
class Value {
constructor (value) {
this.value = value;
}
addValue (x) { return this.value + x; }
}
const five = new Value(5);
// Example data
const numbers = [1, 2, 3];
of(...numbers)
.pipe(
map(five.addValue, five) // This is the reference to the object having value 5
)
.subscribe(transformedData => {
// Do something with the transformed data
console.log(transformedData);
});