What does the colon (:) in JavaScript represent?

后端 未结 2 1595
小鲜肉
小鲜肉 2020-12-06 00:27

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

var stuffToDo = {
    \'bar\' : function() {
        alert(\'         


        
相关标签:
2条回答
  • 2020-12-06 00:55

    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;
      
    0 讨论(0)
  • 2020-12-06 00:58

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

    0 讨论(0)
提交回复
热议问题