【问题标题】:new Function() to anonymous function in Javascriptnew Function() 到 Javascript 中的匿名函数
【发布时间】:2022-11-10 04:14:53
【问题描述】:

需要将下面的 newFunction() 转换为其等效的匿名函数

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

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

}

shapeName 使用 100 个不同的值调用,例如 Rectangle、Square、Circle 等。

我试过的是

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

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

  }

问题在于 newFunction 参数被视为变量/对象,而我的匿名函数变量被视为 String 。

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

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

虽然我的代码在运行时

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

如何修改我的匿名函数以与 newFunction() 相同

【问题讨论】:

  • new Functioneval 相似,而且几乎总是错误的方法。避免像瘟疫一样将代码放在字符串中。例如,传递形状本身而不是shapeName,然后执行return (i, p) => this.create(shape._TYPE, i, p);

标签: javascript anonymous-function


【解决方案1】:

不要进行任何字符串操作,而是自己编写实际代码:

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

并且不要将形状的名称作为字符串传递。传递形状对象本身:

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

如果代码的其他部分将形状名称作为字符串传递,则使用对象将字符串映射到形状:

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

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

【讨论】:

    【解决方案2】:

    如 cmets 中所述,不建议使用这种方法,当然有更好的方法来设计此功能,但如果不了解更多细节就无法提供帮助。

    但是要回答有关如何实现所需功能的问题,您可以尝试将函数体构建为字符串,然后再对其进行解析。

    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   
    
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-24
      • 2010-11-06
      • 2011-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多