将变量发送到函数的变量?

时间:2010-12-26 03:34:57

标签: javascript

假设我有一个函数,其中一个参数是目标变量的名称..我是否可以像这样向函数发送一个变量:

function otherfunction(input){
...
}

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

test(otherfunction);

我遇到的问题是我正在创建一个greasemonkey脚本,由于一个限制,我需要的一个变量无法从函数中返回。所以这将是另一种选择。我只是不知道如何让它工作..任何帮助将不胜感激!!

1 个答案:

答案 0 :(得分:4)

你的例子(差不多)有效:

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

相关问题