javascript how to simulate function global scope for Json statement?
var testJson=
{
开发者_如何学Python a1: 1,
a2: this.a1+1
}
and the result should be:
var testJson=
{
a1: 1,
a2: 2
}
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;
}
};
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.
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
精彩评论