javascript Function constructed with new Function cannot call other functions

邮差的信 提交于 2020-12-16 07:37:53

问题


Using React-native on android. However, I think my question applies to any javascript environment.

I am constructing a function from text sent from the server (there are good reasons for it).

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

The fnBody has the following: " return helper_called_from_dynamic(inArg1); "

my invocation via MyInvoker is the following

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

I am getting an error (from react-native, but again, I suspect it would be common to all other javascript environments):

cannot find variable: helper_called_from_dynamic

Is it possible to get this to work? That is allowing the dynamically created functions to call other functions? Or do I have to resort to 'eval' ?


回答1:


Solution hinted by @Bergi worked for me. The suggestion

Make the evaled code only call methods of arguments

is what I had done, and that worked. I should have thought about it before posting, but it had not occured to me at the time. Instead of making the helper function global, I attached it to an instance of a class, and passed that instance as an argument to the dynamic function.

Here is the detail

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

Then the body of the dynamic function now can access the helper_called_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");


来源:https://stackoverflow.com/questions/38426601/javascript-function-constructed-with-new-function-cannot-call-other-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!