[英]ES6: Re-defining exported function
Given a 3rd party library that exports a function and uses this function in its internal logic - is there any way to re-define this function? 给定第三方库导出函数并在其内部逻辑中使用此函数 - 有没有办法重新定义此函数? For example:
例如:
third-party.js 第三party.js
export function a() {
console.log('a');
}
export function b() {
a();
}
my-module.js 我-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'
A few highlights: 一些亮点:
a
and not a
itself. a
而不是a
自己的函数 。 Exported module is read-only. 导出的模块是只读的。 So, you can't do such.
所以,你不能这样做。
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
If you wish tp.b()
need the value overridden, then you don't export them but call in an instance. 如果你希望
tp.b()
需要重写值,那么你不要导出它们但是调用实例。 In your example code, just export a
not b
. 在您的示例代码中,只导出
a
不是b
。 But since, you're trying to override it from the third-party library. 但是,因为,你试图从第三方库中覆盖它。 It's not possible to do so.
这是不可能的。
But if you insist using them, then you must override both functions. 但如果你坚持使用它们,那么你必须覆盖这两个功能。
const obj = {...tp}
obj.a = () => {
console.log('c')
}
obj.b() // 'a'
obj.b = () => {
obj.a()
}
obj.b() // 'c'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.