Dynamic method calls with javascript

One unique feature of javascript, in contrast to other languages, is the ability
to have dynamic method calls (without getting hackish).
Although this can be handy in many situations, it is often used with
javascript libraries such as jQuery to dynamically call a method on a referenced
element.

Here is a simple, and somewhat crude example:

Target Element

Here is the code behind this:

 $(document).ready(function() {
    $('#showhide').change(function(){
        var val = $(this).val();
        if (val == 0) {
            return;
        }
        $('#target-element')[val == 'showtarget' ? 'show' : 'hide']();
    });
 });

On line 7 is where the magic happens. Here we are using the $(‘#target-element’) show() and hide() methods.
In javascript object properties can be reference one of two ways:

  • object.property
  • object[property]

The code from above could have be written as:

 $(document).ready(function() {
    $('#showhide').change(function(){
        var val = $(this).val();
        if (val == 0) {
            return;
        }
        if (val == 'showtarget') {
            $('#target-element').show();
        }
        else {
            $('#target-element').hide();
        }
    });
 });

As you can see, we now have six lines where we just had one in the previous example. Being able to access the objects properties and methods by the use of
[] allows us a little more wiggle room and a wide range of potential uses.

Learn JavaScript JS

~ by ityndall on October 13, 2010.

Leave a Reply