Please explain me this

Discussion in 'JavaScript' started by XandroZ, Jan 29, 2007.

  1. #1
    I have this code:
    
    var text = "{meth: 'adder', operand1: 2, operand2: 3};";
    var jObject;
    eval('jObject = '+ text);
    eval(jObject.meth + '(' + jObject.operand1 + ',' +
    jObject.operand2 + ');');
    function adder(op1, op2)
    {
    var sum = op1 + op2;
    alert(op1 + " + " + op2 + " = " + sum);
    }
    
    Code (markup):
    I know what the eval function do but I don't understant how "meth,operand1,operand2" become properties of the object jObject.(yes i get that JObject take the text from var text).
    What is the role of ":" and "{" in this case;
     
    XandroZ, Jan 29, 2007 IP
  2. ccoonen

    ccoonen Well-Known Member

    Messages:
    1,606
    Likes Received:
    71
    Best Answers:
    0
    Trophy Points:
    160
    #2
    { .... } is a shorthand way to define array values.

    Essentially, its converting meth: 'adder', eval it so it's a key value or an associative array:

    so you can do alert(jObject.meth); alert(jObject.operand1); alert(jObject.operand2);

    It just starts out with an array of strings, then converts them to an associative array
     
    ccoonen, Jan 29, 2007 IP