Search code examples
javascriptfunctionanonymous-functionobject-literal

Javascript 'colon' for labeling anonymous functions?


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?


Solution

  • 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.