在函数声明而不是运行时分析所有变量

Parse all variables at function declaration instead of run-time

本文关键字:变量 运行时 函数 声明      更新时间:2024-06-01

我想附加一个来自字符串的事件。我遇到的问题是,函数名不是作为字符串传入的,而是在调用函数时编译的,这会导致未定义的变量错误(temp)。

function someFun(arg) {
   alert(arg) ;
}
  temp[0] = "someFunc(test)" ;//this would be a sample of the incoming HTML
  var x = 0 ;
  while(temp[x] != '') {
    temp[x] = temp[x].replace(')','').split('(') ;//remove paranthesis and separate  func name from args
    temp[x][1] = temp[x][1].split(',') ;//turn string of args into array
    func = function() { window[temp[x][0]].apply(el,[]) ; }
    el.addEventListener('click',func,false) ;
    x++ ;
  }

如果我不使用temp[x][0](应该是'someFunc'),而是直接为.apply方法传递一个字符串(在这种情况下是.apply('someFunc…)),我就没有问题了,函数将按预期用onClick调用。否则,当我点击元素el时,我会得到一个没有定义temp的错误。

我非常确信,如果在分配函数之前将temp[x][0]分配给变量,它应该可以工作。像这样的

if (attributes._onClick) {
  temp = attributes._onClick;
  var x = 0;
  while(temp[x] != '') {
    var funcSig = temp[x].replace(')','').split('('); //remove paranthesis and separate func name from args
    var funcName = funcSig[0];
    var funcArgs = funcSig[1].split(','); //turn string of args into array
    func = function() { window[funcName].apply(el,[]); }
    el.addEventListener('click',function(){
      window[funcName].apply(el,funcArgs); }
    ,false);
    x++;
  }
}