我想通过在属性下添加我自己的实用程序函数来扩展某个库中的类util。(用 TypeScript 编写,使用模块扩充)
当我这样调用我的方法时:someClassInstance.util.doSomething(),它们不会收到完整的someClassInstance,而只会收到util我们已经知道的属性。
但是,这些函数SomeClass在调用时需要每个实例的值。
有没有办法接收上限范围 ( someClassInstance) 而不是someClassInstance.utilas this?
我知道仅将实例作为参数传递给函数会更容易实现,但这会使使用我的方法变得不那么好,因为您实际上会重复自己(someClassInstance.util.doSomething(someClassInstance)包含实例两次)
import * as exported from './[SAME_FILE]';
import { SomeClass } from 'SomeLibrary';
declare module 'SomeLibrary' {
interface SomeClass {
util: typeof exported;
}
}
SomeClass.prototype.util = exported;
// Does not work, expects an instance of SomeClass,
// but can only receive SomeClass.util
export async function doSomething(this: SomeClass) {
// do something with `this` (= someClassInstance)
}
示例实现