-->

Javascript 'colon' for labeling anonymous

2019-01-16 06:23发布

问题:

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?

回答1:

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.



回答2:

This is probably inside a map/object declaration like so:

var obj = {
    queryString: function() {
        alert('here');
    },
    eggs: function() {
        alert('another function');
    }
};

obj.queryString();


回答3:

It's a label https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label

var i, j;

loop1:
for (i = 0; i < 3; i++) {      //The first for statement is labeled "loop1"
   loop2:
   for (j = 0; j < 3; j++) {   //The second for statement is labeled "loop2"
      if (i == 1 && j == 1) {
         continue loop1;
      }
      console.log("i = " + i + ", j = " + j);
   }
}

// Output is:
//   "i = 0, j = 0"
//   "i = 0, j = 1"
//   "i = 0, j = 2"
//   "i = 1, j = 0"
//   "i = 2, j = 0"
//   "i = 2, j = 1"
//   "i = 2, j = 2"
// Notice how it skips both "i = 1, j = 1" and "i = 1, j = 2"


回答4:

The : is used when defining an object and its properties.

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

Now obj.queryString is your function.



回答5:

What the

queryString: function() {

//some code

}

means is the you can use queryString() to call the function that it refers to. This kind referencing is generally used if you want to define a class(or a pseudo class ;P) in your javascript. Something like this,

var application= { namespace: {} };

application.namespace.class_name = function(){

  function constructor(){
   return {
     exposed_property1 : property1,
     exposed_property2 : property2,  
     ...
     ...
    }
   }
  //Write property/functions that you want to expose.
  // Write rest of the function that you want private as function private(){}
};

So now at anyother part of the code you can create objects for class_name and use it to access the property1,property2 etc.,