1

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
}
3
  • Do you mean var testJson= { a1: 1 }; testJson.a2 = testJson.a1 + 1;? What you want can only be done through a function call, but not object notation, at least not in a way you're looking to do...unless I'm completely misunderstanding. Commented May 21, 2010 at 18:47
  • Why would you ever need to do that? Commented May 21, 2010 at 19:05
  • @Nick Craver : You are right,I just want to wirte less code. the right way is: var testJson= { a1: 1, a2: testJson.a1+1 } Commented May 22, 2010 at 2:09

3 Answers 3

1

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;
  }
};
Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

Well, that's not really JSON, it's just Javascript syntax.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.