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 this.foo; },
   foo: 'Hello World'
}

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

Consider:

var fn = x.getFoo;
fn();

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

fn.call(x);

Access using array notation

I recently saw something like this in code:

x['getFoo']();

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'];
tmp();

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';
x[name]();

// Equivalent to
var name = 'getFoo',
    fn = x[name];
fn.call(x);

Surprisingly (thanks Matt) this also worked in Chrome!

(x[name])();

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.