What's a more secure alternative for eval() when I just want to call a function?

限于喜欢 提交于 2019-12-10 17:55:46

问题


I know PHP has call_user_func, I was just wondering if JavaScript had something similar, where the method I want to call is, for example: object.set$fieldID($fieldValue)

I would rather not go through if/else/switch blocks just to execute one line of code properly.

If it helps, I am using jQuery.


回答1:


object["set" + $fieldID]($fieldValue);

Some reading material for the above: Member Operators on MDC.

Some advanced methods include Function.prototype.call and Function.prototype.apply. The first is somehow equivalent to PHP's call_user_func() while the latter is somehow equivalent to PHP's call_user_func_array().

The difference between PHP's functions and JavaScript's is that JavaScript allows you to call methods of some object in the context of another object. This is done through the use of the first argument of call() and apply().

An equivalent for the above example, but using call() and apply() looks like this:

object["set" + $fieldID].call(object, $fieldValue);
object["set" + $fieldID].apply(object, [$fieldValue]);

The first argument must be object otherwise the method will be executed with the this pointer bound to the global object, window in the case of browsers.




回答2:


@lonut is correct. More generally though, if you want to call functions that aren't a part of an explicit object (e.g.: global), you can call them on the window object:

var foo = function() { alert(1); };
window['foo']();

since all objects are contained in window.

Another example:

var object = function() { this.method = function() { alert(2); }; }
var instance = new object();
window['instance']['method']();


来源:https://stackoverflow.com/questions/1199110/whats-a-more-secure-alternative-for-eval-when-i-just-want-to-call-a-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!