简体   繁体   English

如何在javascript中使用匿名函数删除新函数

[英]How to remove new Function with Anonymous function in javascript

I am trying to replace eval/new Function with corresponding anonymous function.我正在尝试用相应的匿名函数替换 eval/new Function。

Existing Code -现有代码 -

var y = 2
var fn = new Function("return" +y)
console.log(fn)

When i print fn output is当我打印fn输出是

ƒ anonymous(
) {
return2
}

Refactored code which i am writing -我正在编写的重构代码 -

var y = 2
var fn1 = function()  {return y}
console.log(fn1)

But fn1 in this case is但在这种情况下 fn1 是

ƒ ()  {return y}

Any pointers how can i get the same output as fn ƒ anonymous() {return2} using my own anonymous function.任何指针我如何使用我自己的匿名函数获得与 fn ƒ anonymous() {return2}相同的输出。

You can't (at least not without using another version of eval ).你不能(至少在不使用另一个版本的eval的情况下不能)。

You can get the same effect (ie not having a mutable y ) by using a closure.通过使用闭包,您可以获得相同的效果(即没有可变的y )。

 var y = 2 var fn1 = function(closure_y) { return function() { return closure_y; } }(y) y = 3; console.log(fn1())

If your code depends on a function stringifying itself in a particular way, then you should probably rewrite the code so it no longer depends on that.如果您的代码依赖于以特定方式对自身进行字符串化的函数,那么您可能应该重写代码,使其不再依赖于它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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