【问题标题】:javascript Function constructed with new Function cannot call other functions用new Function构造的javascript函数不能调用其他函数
【发布时间】:2016-07-17 22:39:19
【问题描述】:

在 Android 上使用 React-native。但是,我认为我的问题适用于任何 javascript 环境。

我正在从服务器发送的文本构造一个函数(这是有充分理由的)。

function helper_called_from_dynamic (arg1)
{
  console.log('helper called ',arg1);
}

export class MyInvoker
{
  constructor ()
  {
    this._funcProps={};
  }

  initialize ( item )
  {
    this._funcProps["df1"]=new Function (["inArg1"],item.fnBody);
  }

  call_dynamic_func (fnName,arg1)
  { 
    return this._funcProps[fnName](arg1);
  }
}

fnBody 有以下内容: " return helper_call_from_dynamic(inArg1); "

我通过 MyInvoker 的调用如下

let invInst = new MyInvoker();
let item={fnBody:"return helper_called_from_dynamic(inArg1); "};
invInst.initialize(item);
invInst.call_dynamic_func("df1","somearg");

我收到一个错误(来自 react-native,但我再次怀疑它对所有其他 javascript 环境都很常见):

找不到变量:helper_call_from_dynamic

是否有可能让它工作?那就是允许动态创建的函数调用其他函数? 还是我必须求助于“评估”?

【问题讨论】:

  • 是否定义了this._funcPropsthis._funcProps["df1]=new Function (["inArg1"],item.fnBody);;在"df1 之后缺少"?例如,this._funcProps["df1"] = new Function (["inArg1"],item.fnBody);
  • 您的 JS 代码能否通过缩小/丑化步骤运行,该步骤会删除 helper_called_from_dynamic 函数,因为它没有被使用?我会在你的initialize 中放置一个断点,看看helper_called_from_dynamic 是否在范围内。
  • 你也在调用invInst.call_dynamic_function("df1","somearg");,其中类中的函数是call_dynamic_func,没有“tion”
  • 我的猜测是 helper_called_from_dynamic 实际上并没有在全局范围内声明,就像在 my JSFiddle test 中一样
  • new Function 在全局范围内构造函数。您的 helper_called_from_dynamic 在模块范围内声明。使评估代码仅调用参数方法,使助手全局(不建议)或inject it manually in the eval scope

标签: javascript global-variables ecmascript-6


【解决方案1】:

@Bergi 提示的解决方案对我有用。 建议

使评估代码只调用参数的方法

是我所做的,并且有效。我应该在发帖之前考虑一下,但当时我没有想到。 我没有将辅助函数设为全局,而是将它附加到一个类的实例,并将该实例作为参数传递给动态函数。

这里是详细的

export class MyHelpers
{
 helper_called_from_dynamic (arg1)
 {
   console.log('helper called ',arg1);
 }
}

export class MyInvoker
{
  constructor ()
  {
    this._funcProps={};
    this._myHelpers=new MyHelpers();
  }

  initialize ( item )
  {
    this._funcProps["df1"]=new Function (["inArg1","iHelper"],item.fnBody);
  }

  call_dynamic_func (fnName,arg1)
  { 
    return this._funcProps[fnName](arg1,this._myHelpers);
  }
}

那么动态函数的主体现在可以访问 helper_call_from_dynamic 了:

let invInst = new MyInvoker();
let item={fnBody:"return iHelper.helper_called_from_dynamic(inArg1); "};
invInst.initialize(item);
invInst.call_dynamic_func("df1","somearg");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-29
    • 2018-09-19
    • 1970-01-01
    • 2018-10-17
    • 1970-01-01
    相关资源
    最近更新 更多