title: Javascript automatic getter/setters (John Resig Book)
body: <p>I'm reading "<a href="http://jspro.org/" rel="noreferrer">Pro Javascript Techniques</a>" from John Resig, and I'm confused with an example. This is the code:</p>
  
  <pre><code>// Create a new user object that accepts an object of properties
  function User( properties ) {
    // Iterate through the properties of the object, and make sure
    // that it's properly scoped (as discussed previously)
    for ( var i in properties ) { (function(){
    // Create a new getter for the property
    this[ "get" + i ] = function() {
      return properties[i];
    };
    // Create a new setter for the property
    this[ "set" + i ] = function(val) {
      properties[i] = val;
    };
  })(); }
  }
  
  // Create a new user object instance and pass in an object of
  // properties to seed it with
  var user = new User({
    name: "Bob",
    age: 44
  });
  
  // Just note that the name property does not exist, as it's private
  // within the properties object
  alert( user.name == null );
  
  // However, we're able to access its value using the new getname()
  // method, that was dynamically generated
  alert( user.getname() == "Bob" );
  
  // Finally, we can see that it's possible to set and get the age using
  // the newly generated functions
  user.setage( 22 );
  alert( user.getage() == 22 );
  </code></pre>
  
  <p>Now running that on Firebug console (on FF3) throws that user.getname() is not a function. I tried doing this:</p>
  
  <pre><code>var other = User
  other()
  window.getname() --&gt; this works!
  </code></pre>
  
  <p>And it worked!</p>
  
  <p>Any idea why? thanks everybody!</p>
  
  <p>PS: I strongly recommend this book.</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>doing:</p>
  
  <pre><code>var me = this;
  </code></pre>
  
  <p>seems to work a bit better, but when executing "getname()" it returns '44' (the second property)...</p>
  
  <p>also I find it strange that it worked on the window object without modification...</p>
  
  <p>and a third question, what's the difference between PEZ solution and the original? (he doesn't use an anonymous function)</p>
  
  <p>Thanks to everyone for the feedback! +1</p>