开发者

What does the colon (:) in JavaScript represent?

This is probably a stupid noob question but what does the : represent in the following context:

var stuffToDo = {
    'bar' : function() {
        alert('the value was bar -- yay!');
    },

    'baz' : function() {
        alert('boo baz :(');
    },

    'default' : function() {
        alert('everything else is just ok');
    }
};

if (stuffToDo[foo]) {
    stuffToDo[foo]();
} else {
    stuffToDo['default']();
}

Is it storing the开发者_StackOverflow function to each of those variables?


This is an object literal [MDN]:

var obj = {
    key: value
};

// obj.key === value; // true

It assigns value to a property key of obj. While there are no restriction for what value can be (well, it must be something assignable), there are limitations for key: It must be either an identifier name, a string literal or a numeric literal.

More details can be found in section 11.1.5 of the ECMAScript specification.

The literal notation is similar to:

var stuffToDo = {}; // <-- empty object literal

stuffToDo.bar = function() {...};
// or stuffToDo['bar'] = ...

stuffToDo.baz = function() {...};
// or stuffToDo['baz'] = ...

The biggest difference is that when using an object literal, you cannot access other properties of the object during the declaration.

This will not work:

var obj = {
    foo: value,
    bar: obj.foo
};

whereas this does:

var obj = {};
obj.foo = value;
obj.bar = obj.foo;

For completeness, there are two other uses of colons in JavaScript:

  • Conditional (ternary) operator [MDN]:

    var val = condition ? true-value : false-value;
    
  • Labels [MDN]:

    someLabel: var x = 5;
    


It is the object literal notation http://www.dyn-web.com/tutorials/obj_lit.php

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜