在 es6 中覆盖库函数

Overidding library function in es6

我正在尝试覆盖库中的特定函数。 就我而言,我试图覆盖 Framework7 上的某些功能。该库只是将 class 称为 Framework7,在非 ES6 javascript 中,创建应用程序实例将如下所示:

var app = new Framework7();

所以我认为它是可扩展的,所以这里是我的代码来扩展它:

export class Application extends Framework7 {
    constructor(options) {
        super(options);
    }
}

代码 运行 很好,但是,当我尝试覆盖其中一个函数时,比方说 showPreloader,函数本身永远不会被调用

export class Application extends Framework7 {
    constructor(options) {
        super(options);
    }

    showPreloader(title) {
        console.log('this not printed :(');
        super(title); // this is not called as well

        // but showPreloader() from Framework7 still called
    }
}

我也尝试了不同的方法来覆盖它,我有这样的解决方案:

export class Application extends Framework7 {
    constructor(options) {
        super(options);

        this.showPreloader = (title) => {
            console.log('print me!'); // printed! :D
            super(); // oh, wait! cannot call super from here! :(
        }
    }
}

但是,它看起来有点丑,我不能从那里调用 super。

是否有任何解决方法,以便我可以覆盖库中的函数并通过 super(或任何其他方式?)调用基本函数

I assume it's extendable

不要。阅读文档、询问作者或自己阅读源代码。

在您的情况下,您选择的库并不完全遵循最佳实践,它只是 installs its methods directly on the app "instance". It's a factory function,而不是构造函数。

Is there any workaround so I can override a function from library and calling the base function?

是的,通过在覆盖之前将原始方法存储在变量中。然后你可以使用 .call(this) 调用它(就像在 ES5 中完成继承一样)。

…
    const original = this.showPreloader;
    this.showPreloader = (title) => {
        console.log('print me!'); // printed! :D
        original.call(this, title);
    }

然而,这并不有趣,尤其是因为它不仅仅是一些特定于实例的方法,而且实际上是所有方法。所以你最好在这里放弃 ES6 class 语法和 "subclassing",并使用寄生继承方法:

function MyFramework7(options) {
    const app = new Framework7(options);
    const {showPreloader, …} = app; // all the original methods
    … // mess with the object to your liking
    return app;
}

或者你甚至不需要将它包装在一个函数中,因为我猜 app 是一个单例。