【发布时间】: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 Function与eval相似,而且几乎总是错误的方法。避免像瘟疫一样将代码放在字符串中。例如,传递形状本身而不是shapeName,然后执行return (i, p) => this.create(shape._TYPE, i, p);。
标签: javascript anonymous-function