Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p><em>"The code above neither work with the this keyword nor without it. Why is that?"</em></p> </blockquote> <p>Though you talk about JSON, when reading the text of your question, it sounds like what you're asking is how to use <code>this</code> to refer to the object during its creation when using object literal syntax.</p> <p>The reason <code>this</code> isn't working for you is that its value is defined only within a function, and what defines it is <em>how</em> the function was invoked. </p> <p>Although your code does provide a function, it has no way to refer to the object during creation, because there's no reference available to it until <em>after</em> the literal syntax.</p> <hr> <blockquote> <p><em>"The only working solution is to assign the JSON object to a variable and to use the variable in the code."</em></p> </blockquote> <p>That's right, you can't use <code>this</code> in object literal syntax to refer to the new object, so you'd need to use a variable reference after. </p> <p>Though as an alternative to the literal syntax, you can use a constructor function to create the object. That way you don't need to use the variable to create the <code>fullName</code> property after the object is already created.</p> <pre><code>var obj = new function() { this.firstName = "Foo"; this.lastName = "Bar"; this.fullName = this.firstName + " " + this.lastName; }; </code></pre> <p>This is also useful if you're passing the object to a function.</p> <pre><code>my_func(new function() { this.firstName = "Foo"; this.lastName = "Bar"; this.fullName = this.firstName + " " + this.lastName; }); </code></pre> <hr> <p>So the reason you can use <code>this</code> is that as I stated above, <code>this</code> is defined within a function, and is defined based on how the function was invoked. </p> <p>Here we're using an anonymous function as a constructor by invoking it using <code>new</code>. That makes <code>this</code> refer to a new object being constructed, which is then returned from the constructor function automatically.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload