JSON Link to previous properties

I saw a question similar to mine on Stackoverflow, but most people just provided various jobs that I was not looking for.

I want the property in my JSON to refer to the previous property in the same object:

var x = { a : 1, b : a + 1 }; 

I tried b : this.a + 1 , but this does not work.

Why can't I define "b" in terms of "a"? Again, I'm not looking for workarounds, just understanding and understanding.

thanks

+4
source share
2 answers

You cannot do this. When you create an object, it and its properties do not exist until the instruction is executed. You cannot reference an object or its properties at the creation point.

You can do it as follows:

 var x = {a: 1}; xb = xa + 1; 

PS This is not JSON. This is a JavaScript object. JSON is a string representation of data that just so strongly resembles JavaScript syntax. var x = {a: 1} is an object, '{"a": 1}' (string) is JSON.

+3
source

this is a global object, so in your example it does not have the a property.

You could see this with a simple example in the browser console

 var object = { test: this }; console.log(object); 

You will see that object is a Window object.

0
source

Source: https://habr.com/ru/post/1493227/


All Articles