javascript 如何编写一个接受回调函数的函数并以“安全”的方式运行它?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5594531/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I write a function accepting callBack function and run it in a 'safe' way?
提问by pencilCake
I want to write such a function:
我想写一个这样的函数:
function doGoodJob(someId, callBackfunction){
// some stuff with someId
// todo: RUN callBackFunction here
}
They say eval is 'dangerous' in terms of code injection.
他们说 eval 在代码注入方面是“危险的”。
so, what is the best practice to write a JavaScript function that accepts a call-back function and runs it securely?
那么,编写接受回调函数并安全运行的 JavaScript 函数的最佳实践是什么?
回答by Richard Friend
Is your callback a string or an actual function ?
您的回调是字符串还是实际函数?
If its a function..
如果它是一个函数..
function doGoodJob(someId,callbackFunction)
{
callbackFunction();
}
doGoodJob(1,function(){alert('callback');});
If its a string you can use the Functionconstructor.
如果它是一个字符串,您可以使用Function构造函数。
function doGoodJob(someId,callbackFunction)
{
var func = new Function(callbackFunction)
func();
}
doGoodJob(1,"alert('test');");
Or test for both..
或者两者都测试..
function doGoodJob(someId,callbackFunction)
{
var func = (typeof callbackFunction == 'function') ?
callbackFunction : new Function(callbackFunction);
func();
}
doGoodJob(1,function(){alert('callback');});
doGoodJob(1,"alert('test');");
回答by Thor Jacobsen
This should work:
这应该有效:
function doGoodJob(simeOd, callBackFunction){
/** Do stuff **/
callBackFunction();
}
quick fiddle: http://jsfiddle.net/pS67X/
快速小提琴:http: //jsfiddle.net/pS67X/
回答by user2300875
though late to this topic, just wanted to adde some thing. Above solution works for alert or passing function as argument, but not in the below case.
虽然这个话题迟到了,只是想补充一些东西。以上解决方案适用于警报或将函数作为参数传递,但不适用于以下情况。
doGoodJob(1, "someCallbackFunction");
function someCallBackFunction() {
alert("im called");
}
instead if use eval(callbackFunction) like below
相反,如果使用 eval(callbackFunction) 如下所示
function doGoodJob(someId,callbackFunction) {
var func = (typeof callbackFunction == 'function') ?
callbackFunction : eval(callbackFunction);
func();
}
doGoodJob(1,someCallBackFunction);
doGoodJob(1,"someCallBackFunction");
回答by user3216114
Callback function means function pass as an argument like we pass variable.
When calling the callback function, we could use it like below:
回调函数意味着函数作为参数传递,就像我们传递变量一样。
在调用回调函数时,我们可以像下面这样使用它:
<script>
function callbackExample(arg1, callback){
alert(arg1);
var x = 10, y = 20;
if (callback && typeof(callback) === "function") {
callback(x+y);
}
}
callbackExample("test", function(res){
alert("This is the callback function..." + res);
});
</script>