如何复制/混合一个函数,并修改它在JavaScript中的一些硬编码的字符串?(How to copy/mix a function and modify some hardcoded string

编程入门 行业动态 更新时间:2024-10-28 17:14:36
如何复制/混合一个函数,并修改它在JavaScript中的一些硬编码的字符串?(How to copy/mix a function and modify some hardcoded string in it in javascript?)

所以我们假设我有这个方法:

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).

更多推荐

本文发布于:2023-07-14 20:22:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1107171.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:它在   字符串   一个函数   copy   mix

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!