title: Javascript - Set variable value inside function
body: <p>I'd like to declare some variables, an then let let a function build the actual objects and assign their reference to these previously declared variables.</p>
  
  <p>The way I do it now works, but it gets tedious with many variables.</p>
  
  <pre><code>function bar(obj) {
      var newObject = {'an':'object'};
      obj['element'] = newObject;
  }
  
  function foo() {
      var ref={};
      bar(ref);
      ref=ref.element; // Tedious line
  }
  </code></pre>
  
  <p>For those wondering why I would like to do such a thing, I built a simple function to generate the DOM from JSON. It goes something like that, with <code>#bind</code> used to do what <code>bar</code> does in the previous snippet :</p>
  
  <pre><code>var legend = {};
  $('#element').append(['form',['fieldset',
      ['legend',{'#bind':legend},['text':'Legend title']]
      ]].getDomForThis());
  legend=legend.element;
  </code></pre>
  
  <p>Now I can append some new elements after the legend with something like</p>
  
  <pre><code>for(fieldName in fields) {
    legend.insertAfter(['div',[['input',['name':fieldName]],...]].getDomForThis());
  }
  </code></pre>
  
  <p>I'd like to avoid having to write the tedious line. It's like <code>createElement</code> and <code>appendChild</code>, one function call should be enough !</p>
  
  <p><strong>UPDATE</strong> : After some thought, I believe there is no way to do that with Javascript. I was hoping for some hidden Javascript magic somewhere, but I have reason to think it will not happen.</p>
  
  <p>Basically, I'd like to assign to a variable reference a new value, without creating a new reference. But a function argument <code>a</code> is distinct from the variable <code>v</code> it represents. The object pointed at are the same, but the adress of the two variables are different. Hence, assigning a new value to <code>a</code> cannot change the value of <code>v</code> in any way.</p>
  
  <p>In other words, every variable has its own address, and there's not any other way to change what it points at, than referencing it explictly.</p>
  
  <p>And in my case, because <code>ref</code> is "private" to the function, there's no way to access it from somewhere else.</p>
  
  <p>Too bad...</p>