title: Javascript: Do I need to put this.var for every variable in an object?
body: <p>In C++, the language I'm most comfortable with, usually one declares an object like this:</p>
  
  <pre><code>class foo
  {
  public:
      int bar;
      int getBar() { return bar; }
  }
  </code></pre>
  
  <p>Calling <code>getBar()</code> works fine (ignoring the fact that <code>bar</code> might be uninitialized). The variable <code>bar</code> within <code>getBar()</code> is in the scope of class <code>foo</code>, so I don't need to say <code>this-&gt;bar</code> unless I really need to make it clear that I'm referring to the class' <code>bar</code> instead of, say, a parameter.</p>
  
  <p>Now, I'm trying to get started with OOP in Javascript. So, I look up how to define classes and try the same sort of thing:</p>
  
  <pre><code>function foo()
  {
       this.bar = 0;
       this.getBar = function() { return bar; }
  }
  </code></pre>
  
  <p>And it gives me <code>bar is undefined</code>. Changing the <code>bar</code> to <code>this.bar</code> fixes the issue, but doing that for every variable clutters up my code quite a bit. Is this necessary for every variable? Since I can't find any questions relating to this, it makes me feel like I'm doing something fundamentally wrong.</p>
  
  <hr>
  
  <p>EDIT: Right, so, from the comments what I'm getting is that <code>this.bar</code>, a property of an object, references something different than <code>bar</code>, a local variable. Can someone say why exactly this is, in terms of scoping and objects, and if there's another way to define an object where this isn't necessary?</p>