Aditya
Aditya

Reputation: 431

How to remove new Function with Anonymous function in javascript

I am trying to replace eval/new Function with corresponding anonymous function.

Existing Code -

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

When i print fn output is

ƒ 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

ƒ ()  {return y}

Any pointers how can i get the same output as fn ƒ anonymous() {return2} using my own anonymous function.

Upvotes: 0

Views: 273

Answers (1)

Quentin
Quentin

Reputation: 944202

You can't (at least not without using another version of eval).

You can get the same effect (i.e. not having a mutable y) by using a closure.

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.

Upvotes: 1

Related Questions