tags:

views:

42

answers:

3

javascript how to simulate function global scope for Json statement?

   var testJson=
    {
        a1: 1,
        a2: this.a1+1
    }

and the result should be:

var testJson=
{
    a1: 1,
    a2: 2
}
+1  A: 

You'd have to either define a variable outside testJson, or use a function as the value of a2, like this:

var testJson = {
  a1: 1,
  a2: function () {
    return this.a1 + 1;
  }
};
Jimmy Cuadra
A: 

JSON does not support code execution. The JSON specification is simply a means for serializing and unserializing information for transport. There should be no executable content in a JSON string.

JSON parsers should fail when they encounter a non-literal value in a JSON string.

The only exception to this rule is with JSON-P, which wraps a JSON string in a function call in order to bypass cross-domain mechanisms.

mattbasta
Well, that's not really JSON, it's just Javascript syntax.
Pointy
A: 

I don't think that's possible easily. It may be possible, but it would probably involve creating a function from an object and back again. This would be a lot easier:

var testJson=
{
    a1: 1,
    a2: function(){return this.a1+1}
}

which you could evaluate using

testJson.a2();

this should work out of the box

seanizer