简体   繁体   English

new Function() 到 Javascript 中的匿名函数

[英]new Function() to anonymous function in Javascript

Need to convert the below newFunction() to its equivalent anonymous function需要将下面的 newFunction() 转换为其等效的匿名函数

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. shapeName 使用 100 个不同的值调用,例如 Rectangle、Square、Circle 等。

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 .问题在于 newFunction 参数被视为变量/对象,而我的匿名函数变量被视为 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()如何修改我的匿名函数以与 newFunction() 相同

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

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   

  }

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

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