假设我有一个函数,而参数之一是目标变量的名称。那么我是否可以像这样将变量发送给函数:

function otherfunction(input){
...
}

function test {target) {
var x = 1;
target(x);
}

test(otherfunction);


我遇到的问题是我正在制作一个润滑脂脚本,由于限制,无法从函数中返回我需要的变量之一。因此,这是替代方法。我只是不知道如何使它工作。任何帮助将不胜感激!

最佳答案

您的示例(几乎)有效:

function otherfunction(input){
   alert(input);
}

function test(target) {
   if(typeof target !== 'function') {
      alert('target is not a function!');
      return;
   }
   target(1); //invokes the passed-in function, passing in 1
}

test(otherfunction); //alerts 1

//You can also do it with an anonymous function too:

test(function(arg) {
  alert(arg * 5);
}); //alerts 5


jsFiddle example

关于javascript - 将变量发送到函数的变量?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4532651/

10-12 12:19
查看更多