[JavaScript] Object – Getters and Setters

It is frequently asked whether JavaScript supports properties (getters and setters). The answer is “Yes” and let’s find out how they can be defined.

ES2015 introduced the class syntax with getters and setters. Please refer to my new post: [JavaScript – ES2015] Class – How to Define it.

 

1. __defineGetter__(), __defineSetter__() Methods

Object” provides 2 non-standard methods:

  • __defineGetter__(“propertyname”, fun)
  • __defineSetter__(“propertyname”, fun)
function Product(name) {
  this.name = name;
  this._p = 0;

  this.__defineGetter__("price", function () {
    return this._p;     });
  this.__defineSetter__("price", function (value) {
    if (parseFloat(value) >= 0)
      this._p = value;
    else
      alert("You cannot set the negative value to the price");
  });
}

function Test() {
  var myProduct = new Product("Toy");
  myProduct.price = 9.99;
  alert(myProduct.price); // 9.99
  myProduct.price = -9.99; // error
  alert(myProduct.price); // 9.99
}

These functions are not standard (only for Mozilla browsers) and should not be used in general.

 

2. get / set Functions

There is another non-standard syntax.

When you create an object, you can specify “get” or “set” keywords before functions.

function Test() {
  var myProduct = {
    name: "Toy",
    _p: 0,
    get price() {
      return this._p;
    },
    set price(value) {
      if (parseFloat(value) >= 0)
        this._p = value;
      else
        alert("You cannot set the negative value to the price");
    }
  };

  myProduct.price = 9.99;
  alert(myProduct.price); // 9.99
  myProduct.price = -9.99; // error
  alert(myProduct.price); // 9.99
}

This approach works in most browsers (even IE) but it is limited to the current object.

 

3. ECMAScript 5 – defineProperty()

The recommended way to create a property is to use the “defineProperty()” method. But it is defined in the ECMAScript 5.

  • Object.defineProperty(obj, prop, descriptorObj)
function Product(name) {
  this.name = name;
  this._p = 0;
}

Object.defineProperty(Product.prototype, "price", {
  get: function() {
    return this._p;
  },
  set: function(value) {
    if (parseFloat(value) >= 0)
      this._p = value;
    else
      alert("You cannot set the negative value to the price");
  }
});

function Test() {
  var myProduct = new Product("Toy");
  myProduct.price = 9.99;
  alert(myProduct.price); // 9.99
  myProduct.price = -9.99; // error
  alert(myProduct.price); // 9.99
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s