所以我们假设我有这个方法:
myMethod1() { const a = 1; const b = 2; return callsAnotherFunction(`foo: ${a + b} $`); }现在我想在另一个函数中使用它,但是使用bar而不是foo 。
myMethod2() { const a = 1; const b = 2; return callsAnotherFunction(`bar: ${a + b} $`); }这可能没有修改myMethod1 ?
以某种方式,如果myMethod1变成其他的东西,让我们说:
myMethod1() { const a = 1; const CHANGE = 2; return callsAnotherFunction(`foo: ${a + CHANGE} $`); }我不必碰myMethod2因为它只是克隆myMethod1并将foo更改为bar从而自动给我:
myMethod2() { const a = 1; const CHANGE = 2; return callsAnotherFunction(`bar: ${a + CHANGE} $`); }也许像将函数解析成字符串,替换某些文本并输出新函数一样? 像这样的东西:
myMethod2() { const hypothetical = @toString(myMethod1) hypothetical.replace('foo', 'bar'); return @toFunction(hypothetical); }^上面的代码显然不起作用,因为该语法不存在,只是为了说明我想要做什么。
这是甚么可能吗?
谢谢你的帮助。
编辑:我无法编辑/访问方法1
So let’s say I have this method:
myMethod1() { const a = 1; const b = 2; return callsAnotherFunction(`foo: ${a + b} $`); }Now I would like to have it in another function as well but with bar instead of foo.
myMethod2() { const a = 1; const b = 2; return callsAnotherFunction(`bar: ${a + b} $`); }Is this possible without modifying myMethod1?
In a way that if myMethod1 gets changed to something else, lets say:
myMethod1() { const a = 1; const CHANGE = 2; return callsAnotherFunction(`foo: ${a + CHANGE} $`); }I do not have to touch myMethod2 because it just clones myMethod1 and changes the foo to bar thus giving me automatically:
myMethod2() { const a = 1; const CHANGE = 2; return callsAnotherFunction(`bar: ${a + CHANGE} $`); }Maybe something like parsing the function into a string, replacing the certain text and outputting a new function? Something like this:
myMethod2() { const hypothetical = @toString(myMethod1) hypothetical.replace('foo', 'bar'); return @toFunction(hypothetical); }^ the code above is obviously not working because that syntax does not exist, it’s just to clarify what I would like to do.
Is something like this even possible?
Thanks for your help.
Edit: I can’t edit/access method1
最满意答案
如果你不能修改该函数,那么你不能修改它的正文中的硬编码字符串。 使用函数构造函数不是一个好主意,并且由于内容安全策略可能会阻止使用eval/Function (它们被认为是相同的),所以在许多情况下不起作用。
If you cannot modify the function then you cannot modify hardcoded strings in its body. Using the function constructor is not a good idea and will not work in many cases due to Content Security Policies which can prevent the use of eval/Function (which are considered the same).
更多推荐
发布评论