Search code examples
javascriptvariablesobjectthis

Accessing variables in objects in javascript without "this"


function Peon(number) {
  this.number = number;

  this.inc = function() {
    number = number + 1;
  };

  return true;
}
var p = new Peon(10);

function returnNumber() {
  p.inc();
  alert(p.number);
}
<input id="b00" type="button" value="Click" onclick="returnNumber()">

This code doesn't work as intended. Is there a way to make it work without having to write

this.number=this.number+1;

Here it is a trivial choice, but in bigger codes not having this.* would make it a lot more readable. Is it possible?


Solution

  • You can make number "private", but then you need a getter:

    function Peon(number) {
      var number = number;
    
      // increment
      this.inc = function() {
        number++;
      };
    
      // a simple getter
      this.getNumber = function() {
        return number;
      }
    }
    
    var p = new Peon(10);
    
    function returnNumber() {
      p.inc();
      alert(p.getNumber());
    }
    <input id="b00" type="button" value="Click" onclick="returnNumber()">

    You should read Douglas Crockfords "The Good Parts" for more information on how to use this pattern, there's (limited) a preview available at Google Books.

    Also you don't need to return something from the constructor, your return true is superfluous.