admin管理员组文章数量:1289556
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.
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.
Share Improve this question edited Jul 29, 2009 at 10:03 soulmerge 75.8k20 gold badges121 silver badges160 bronze badges asked Jul 29, 2009 at 9:47 Will MorganWill Morgan 4,4905 gold badges30 silver badges42 bronze badges2 Answers
Reset to default 9object["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.
@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']();
版权声明:本文标题:javascript - What's a more secure alternative for eval() when I just want to call a function? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741395231a2376338.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论