0

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

1
  • 2
    new Function is similar to eval, and is almost always the wrong approach. Avoid putting code in strings like the plague. For example, pass the shape itself instead of the shapeName, then do return (i, p) => this.create(shape._TYPE, i, p);. Commented May 24, 2022 at 10:38

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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   

  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.