【问题标题】:Modify class method arguments修改类方法参数
【发布时间】:2020-11-14 16:09:49
【问题描述】:

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

第一个提供以下类:

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

第二个是像这样使用以前的加载器

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

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

我不能修改原始类

我尝试过的:

// 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 :(

没有工作:(

【问题讨论】:

  • @CertainPerformance 添加:)

标签: javascript class prototype


【解决方案1】:

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

用途:

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

【讨论】:

  • 几乎明白了!太好了,它现在可以工作了。谢谢! :)
猜你喜欢
  • 2018-12-12
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
  • 2010-10-11
  • 2020-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多