Home > Software design >  new Function() to anonymous function in Javascript
new Function() to anonymous function in Javascript

Time:05-24

Need to convert the below newFunction() to its equivalent anonymous function

MyFunc.createShape=function(shapeName,i,p){

  var funcBody="this.create(" shapeName "._TYPE,i,p);"
  var finalFunc=new Function(i,p,funcBody);

}

shapeName is called with 100s of different values like Rectangle,Square,Circle,etc.

What I have tried is

  var global="";
  MyFunc.createShape=function(shapeName,i,p){

    global=shapeName;
    var finalFunc=function(i,p){
         this.create(global "._TYPE",i,p);
    };    

  }

The issue is in newFunction parameter is treated as a variable/object while my anonymous function variable is treated as a String .

new Function(i,p,funcBody); 
At runtime is evaluated as

function(i,p){
         this.create(Rectangle._TYPE,i,p);
    };

While my code at runtime

function(i,p){
         this.create("Rectangle._TYPE",i,p);
    };

How do I modify my anonymous function to behave same as the newFunction()

CodePudding user response:

Don't do any string manipulation, instead write the actual code itself:

MyFunc.createShape=function(shape,i,p){
    function finalFunc (i,p) {
         this.create(shape._TYPE,i,p);
    };    
}

And don't pass the name of the shape as string. Pass the shape object itself:

MyFunc.createShape(Rectangle, i, p); // Don't pass "Rectangle", pass Rectangle

If other parts of your code pass around the shape name as a string then use an object to map the string to the shape:

const shapes = {
    Rectangle: Rectangle,
    Circle: Circle,
    Triangle: Triangle,
}

MyFunc.createShape(shapes["Rectangle"], i, p);

CodePudding user response:

As stated in the comments, using this approach is not advisable and there are certainly better ways to design this functionality, but it's impossible to help without knowing more details.

But to answer your question on how to achieve what you want, you can try building the function body as a string before parsing it like.

MyFunc.createShape=function(shapeName,i,p){
    global=shapeName;
    
    return new Function(`function(i,p){
         this.create(${global}._TYPE,i,p);
    }`).bind(this); // if you don't wish to execute in current scope omit this   

  }
  • Related