修改 class 方法参数

Modify class method arguments

我正在使用两个不同的库。

第一个提供以下class:

class VolumeLoader {
    load(string: string): Promise<any> // Returns a promise to attach callbacks
    // rest of methods
}

第二个是这样使用之前的loader

const loader = new Loader()
loader.load(string, callback) // Provides an argument to attach callback (without promises)

如何修改 VolumeLoader 使其可以接受 string, callback

我无法修改原始文件 CLASS

我尝试过的:

// Creating a new class using the previous loader. The load function works but I lose the rest of methods.
class _VolumeLoader {
    loader = new VolumeLoader
    load (string, callback) {
        this.loader.load(string).then(callback)
    }
    // rest of methods are lost! :(
}
// Modifying directly the prototype
const OriginalVolumeLoader = VolumeLoader;
const _VolumeLoader = VolumeLoader

_VolumeLoader.prototype.load = function (string, callback) {
    OriginalVolumeLoader.prototype.load.call(this, string).then(callback)
}
// Creates an infinite loop, not sure why :(

None 有效:(

您需要单独保存原始load方法以避免无限循环。执行 OriginalVolumeLoader = VolumeLoader 只会在内存中创建对相同 class 的另一个引用,因此对 OriginalVolumeLoader 的更改最终也会对 VolumeLoader 进行更改。

使用:

const origLoad = VolumeLoader.prototype.load;
VolumeLoader.prototype.load = function (string, callback) {
    origLoad.call(this, string).then(callback)
};