繁体   English   中英

通过变量将函数表达式传递到新的Function()中

[英]Passing a function expression into new Function() with a variable

这是有史以来最令人困惑的事情。 标题可能没有多大意义。 我尽力了。 希望我能说清楚。 好的,我正在看Google Channel API的井字游戏示例。

在javascript部分中。

他们有这样的事情;

sendMessage = function(param) {
  alert(param);
  //this part actually sends message to server, 
  //for simplicity lets assume it pops up alert.    
  }

init = function(){
  var input = 3;
  var submitButton = document.getElementById('submitButton');
  submitButton.onclick = new Function('sendMessage(' + input + ')');
}

setTimeout(init, 100);

这会弹出警报并打印3。我不确定这是如何工作的。 但这有效。 如果可以解释这一点,那也很好。 我找不到在其他地方使用这种新Function()的地方。

问题是,如果输入是字符串,

var input = "test";

这不起作用,并且没有弹出警报。

感谢您的解释和帮助。

Function构造Function通过将其参数eval为函数体来工作。

... = new Function('sendMessage(' + input + ')');

类似于

... = eval("function(){sendMessage("+input+")}";

对于数字input s,这是可行的,因为它们的文本表示形式可以用作数字文字。 对于文本输入,不是。 这样做可以获得有限的支持

... = new Function('sendMessage("'+input+'")');

更一般的方法是使用

... = new Function('sendMessage("'+JSON.stringify(input)+'")');

但是,我建议使用立即调用的函数表达式(IIFE)来代替,以避免任何形式的eval以及对JSON对象的依赖,这在非常老的浏览器(IE <8)中是不存在的:

... = (function(input){
  return function(){
    sendMessage(input)
  }
})(input)

或者,如果input变量不变,则无需捕获其值:

... = function(){ sendMessage(input) }

或者,如果不在sendMessage中使用this函数,则可以使用bind (IE8需要填充):

... = sendMessage.bind(undefined, input)

当输入为字符串时,函数调用变为:

sendMessage(string)

实际上应该是:

sendMessage("string")sendMessage('string')

sendMessage = function(param) {
  alert(param);   
  }

init = function(){
  var input = '"string"';
  var submitButton = document.getElementById('submitButton');
  submitButton.onclick = new Function('sendMessage(' + input + ')');
}

setTimeout(init, 100);

这是摆弄您如何使用的小提琴

函数的参数被求值..也就是说,它被执行了。 这就是为什么它起作用。

当您传递字符串时,它行不通只是因为您传递的字符串将被视为对象或变量而不是字符串..我们都知道它不存在。

这有效:

submitButton.onclick = new Function('sendMessage(3)');

这不是:

submitButton.onclick = new Function('sendMessage(test)'); //because test does not exist

但这会

submitButton.onclick = new Function('sendMessage("test")');

因此,如果您将代码更改为:

submitButton.onclick = new Function('sendMessage("' + input + '")');

那一切都很好

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM