JavaScript/Reserved words/this

From Wikibooks, open books for an open world
Jump to navigation Jump to search
Previous: synchronized Reserved words Next: throw

The this keyword[edit]

The this keyword allows a method to read and write the property variables of that instance of the object.

The following example uses an initial capital letter for PopMachine() to help indicate that the object needs to be created with the new keyword. You can use the new keyword with any function to create an object, but it will be much easier to keep track of what you're doing, if you only use new with functions that are meant just for the purpose, and mark those functions by naming them with an initial capital letter.

Examples[edit]

Example 1
function PopMachine() {
  this.quarters = 0;
  this.dollars = 0;
  this.totalValue = function () {
    var sum = this.quarters*25 + this.dollars*100;
    return sum;
  }
  this.addQuarters = function (increment) {
    this.quarters += increment;
  }
  this.addDollars = function (increment) {
    this.dollars += increment;
  }
}
function testPopMachine() {
  var popMachine = new PopMachine();
  popMachine.addQuarters(8);
  popMachine.addDollars(1);
  popMachine.addQuarters(-1);
  alert("Total in the cash register is: " + popMachine.totalValue());
}
testPopMachine();

Please notice that the above method is inefficient and will use way too much memory inside the browser, if you need to create a serious JavaScript class then you must first learn about prototypes.

Example 2
money = {
    'quarters': 10,
    'addQuarters': function(amount) {
        this.quarters += amount;
    }
};
money.addQuarters(10);

The total number of quarters would now be twenty.

Previous: synchronized Reserved words Next: throw