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()
new Functionis similar toeval, and is almost always the wrong approach. Avoid putting code in strings like the plague. For example, pass the shape itself instead of theshapeName, then doreturn (i, p) => this.create(shape._TYPE, i, p);.