1. Computing

JavaScript By Example

Object Oriented: 7. Getters and Setters


Both the properties and methods of an object are available throughout the time that the object exists. While each of these can be accessed directly this is often not the best way of handling things.Rather than directly accessing properties from anywhere in your code, you get better control of the property if you make it private to the object and use getter and setter methods to read and write the property. By doing this you make it easier to control any validation that needs to be performed before writing the property (by adding it inside the setter method) and can simplify the formatting of the value (by applying it in the getter method).

In this example we create an object which has a private property called phone. This means that the property cannot be accessed from outside of the object. By defining getter and setter methods for this property within the object constructor function we provide access to this private property. We could easily add code into these two methods to validate that it is a phone number and to strip out all formatting in the setter method and to add back specific formatting in the getter method.

var myexample;
example = function() {
var phone;
this.getPhone = function() { return phone; }
this.setPhone = function(x) { phone = x; }
myexample = new example()
myexample.setPhone('02 9999 9999');

Note that alert is used here for the purpose of simplifying the example. You should never use alert() in your own code for anything other than displaying results during testing.

  1. About.com
  2. Computing
  3. JavaScript
  4. Javascript Tutorials
  5. JavaScript By Example
  6. Object Oriented
  7. JavaScript By Example - Object Oriented: Getters and Setters

©2014 About.com. All rights reserved.