In your example there is no difference between
jQuery(this)[ state ? "show" : "hide" ]();
and
state ? jQuery(this).show() : jQuery(this).hide();
However, squares can be used to call a function without a name:
var myFunctionName = 'show'; jQuery(this)[ myFunctionName ]();
Why is this useful? In the above example, this is completely useless. But we can find some situations where it can be nice:
// list of available methods var effects = [ 'hide', 'slideUp', 'fadeOut' ]; // get a random index between 0 and effects.length-1 (2 in this case) var randomIndex = Math.floor(Math.random() * (effects.length)); // get the method name var methodToCall = effects[ randomIndex ]; jQuery(this)[ methodToCall ]();
This snippet will select one random method and call this method on the jQuery object. Isn't that so good? :)
pomeh
source share