当我只想调用函数时,eval()的更安全的替代方法是什么? [英] What's a more secure alternative for eval() when I just want to call a function?

查看:100
本文介绍了当我只想调用函数时,eval()的更安全的替代方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道PHP有 call_user_func ,我只是想知道JavaScript是否有类似的东西,我要调用的方法是,例如: object.set $ fieldID($ fieldValue)

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)

我宁愿不通过if / else / switch块来执行一行代码正确。

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

如果有帮助,我正在使用jQuery。

If it helps, I am using jQuery.

推荐答案

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

以上的一些阅读材料: MDC上的/en/Core_JavaScript_1.5_Reference/Operators/Member_Operatorsrel =noreferrer>会员运营商

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

一些高级方法包括 Function.prototype.call Function.prototype.apply 。第一个是以某种方式等同于PHP的 call_user_func(),而后者某种程度上等同于PHP的 call_user_func_array()

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().

PHP的函数与JavaScript之间的区别在于JavaScript允许您在另一个对象的上下文中调用某些对象的方法宾语。这是通过使用 call() apply()的第一个参数来完成的。

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().

以上示例的等价物,但使用 call() 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]);

第一个参数必须是 object 否则方法将使用绑定到全局对象的指针执行,对于浏览器, window

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.

这篇关于当我只想调用函数时,eval()的更安全的替代方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆