0

I'm seeing : used in JavaScript a good bit and I can not figure out what exactly what its doing. Is it naming something? For example is the function being named onSave? Example is below.

 onSave: function() {
        var properties = this.getFormData(),
            request = this.wfsBody("usa", "usa:pecotest", "geom",                  
            properties);
            console.log(request);
            this.makeRequest(request);enter code here
lux
  • 8,315
  • 7
  • 36
  • 49

2 Answers2

3

There are, as far as I know, four uses of : in JavaScript. The ternary operator, switch statements, labels, and part of JavaScript object creation.

// if a, then f is b. Otherwise it is C.
var f = a? b: c; 
// This creates an object. You can now look at the object's `name` property.
var obj = {name: val}

switch(foo)
{
   case 1:
     // this only happens if foo === 1
     break;
}

top: // this is a label
for (i = 0; items.length; i++)
  for (j = 0; j < tests.length; i++)
    if (!tests[j].pass(items[i])){
      allPass = false;
      break top; // breaks the outermost loop.
    }

You'll see this also in JSON, which is JavaScript object notation:

{
    "foo": 1,
    "bar": [2,3],
    "baz": {
         "bat": 4
    }
}

That is an object where

obj.foo === 1
obj.bar[0] === 2
obj.bar[1] === 3
obj.baz.bat === 4

The most common use, and certainly what most people expect when they see the above code, is that an object is being created with a property "onStart" which is a function defined as above.

cwallenpoole
  • 79,954
  • 26
  • 128
  • 166
1

: is used as an = in an object - separating the object property from its value. Objects can also have functions as values. So what you're seeing is:

var obj = {
onSave: function(){}
}

could also be obj.onSave = function(){}

itamar
  • 3,837
  • 5
  • 35
  • 60
  • thanks man you nailed it for me. I took a look around some more code and figured out that what I'm looking at is objects for a class file. I'm just use to seeing it differently. –  Dec 18 '15 at 22:57