Javascript 'colon' for labeling anonymous functions?

knownasilya picture knownasilya · Feb 21, 2012 · Viewed 30.5k times · Source

What does this code refer too?

queryString: function() {

//some code

}

I tested it in the WebConsole (Firefox) but it wouldn't execute, so I'm thinking that it isn't equivalent to function queryString() {}.

So what is it exactly?

Answer

Alex Wayne picture Alex Wayne · Feb 21, 2012

You are missing some code there, but I assume its part of an object declaration like this:

var obj = {
  queryString: function() {
    //some code
  }
};
obj.queryString();

It assigns a function as a property of an object literal. It would be equivalent to this:

var obj = {};
obj.queryString = function() { ... };
obj.queryString();

In general, the object literal syntax looks like this:

{ key: value, otherKey: otherValue };

So the reason this didn't work in the console is that it was not enclosed in {} characters, denoting an object literal. And this syntax is valid ONLY in an object literal.