简体   繁体   English

ES6:重新定义导出的函数

[英]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: 一些亮点:

  • I don't need it for testing, but for production (yes, I know it would be a dirty hack) 我不需要它进行测试,但是对于生产(是的,我知道这将是一个肮脏的黑客)
  • Yes, I'm aware of imports being live read-only views , I'm looking for a workaround to overcome this constraint 是的,我知道导入是实时只读视图 ,我正在寻找一种解决方法来克服这种限制
  • No, I can't change the code of the 3rd party library 不,我无法更改第三方库的代码
  • I need my change to actually change the logic of the 3rd party. 我需要改变才能真正改变第三方的逻辑。 I'd like to call a function that calls 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM