Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 351
knownasilya Avatar asked Feb 21 '12 20:02

knownasilya


People also ask

How do you declare anonymous function in JavaScript?

Anonymous Function is a function that does not have any name associated with it. Normally we use the function keyword before the function name to define a function in JavaScript, however, in anonymous functions in JavaScript, we use only the function keyword without the function name.

What does () => mean in JavaScript?

It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.

What is the syntax for an anonymous function?

The () makes the anonymous function an expression that returns a function object. An anonymous function is not accessible after its initial creation. Therefore, you often need to assign it to a variable. In this example, the anonymous function has no name between the function keyword and parentheses () .

What is anonymous function in JavaScript?

In JavaScript, an anonymous function is that type of function that has no name or we can say which is without any name. When we create an anonymous function, it is declared without any identifier. It is the difference between a normal function and an anonymous function.


1 Answers

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.

like image 111
Alex Wayne Avatar answered Oct 03 '22 08:10

Alex Wayne