JeB*_*JeB 6 javascript ecmascript-6 es6-modules
给定一个第三方库,该库导出一个函数并在其内部逻辑中使用此函数-是否有任何方法可以重新定义此函数?例如:
third-party.js
export function a() {
console.log('a');
}
export function b() {
a();
}
Run Code Online (Sandbox Code Playgroud)
my-module.js
import * as tp from 'third-party';
//Re-define, something like this
Object.defineProperty(tp, 'a', { writable: true, value: () => console.log('c')});
//Call b and get the re-define function called
tp.b(); //Expected output: 'c'
Run Code Online (Sandbox Code Playgroud)
一些要点:
a而不是a本身的函数。导出的模块是只读的。所以,你不能这样做。
delete tp.a;
tp.a = () => {
console.log('c')
}
tp.a() // 'c'
tp.b() // You'll still get 'a'
// it's because, b is calling exported function a
Run Code Online (Sandbox Code Playgroud)
如果您希望tp.b()需要覆盖该值,则不要导出它们,而是在实例中调用。在您的示例代码中,只需导出anot b。但既然,您试图从第三方库覆盖它。这是不可能的。
但如果您坚持使用它们,那么您必须重写这两个函数。
const obj = {...tp}
obj.a = () => {
console.log('c')
}
obj.b() // 'a'
obj.b = () => {
obj.a()
}
obj.b() // 'c'
Run Code Online (Sandbox Code Playgroud)