Javascript function invocation using square brackets

This one caught me by surprise. Thinking about it, it makes sense.

Basic functions

Consider the object:

var x = {
   getFoo: function () { return; },
   foo: 'Hello World'

When we try x.getFoo() we see “Hello World”.


var fn = x.getFoo;

In this case the result is undefined. The function does not have the right value of “this”. We can work around:;

Access using array notation

I recently saw something like this in code:


With my background in C and Java like languages I’d naturally read this as “dereference x[‘getFoo’] then invoke”. In other words:

var tmp = x['getFoo'];

If I type the above into Chrome’s debugger I see undefined as before. However if I type x[‘getFoo’]() it works! It seems that object[functionName]() is a valid invocation of the function in the context of the object.

It doesn’t make sense to use this notation if the function name is hard coded and does not contain characters that would be invalid in a variable name, but it does allow calls to be made where the function name is variable or the function name contains bad characters.

var name = 'getFoo';

// Equivalent to
var name = 'getFoo',
    fn = x[name];;

Surprisingly (thanks Matt) this also worked in Chrome!


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.