javascriptmodule-pattern

Difference between get/set and Object.defineProperty in the Module Pattern


I've seen two different ways of implementing getters/setters in a module pattern. One uses "defineProperty", while the other doesn't. What are the advantages/disadvantages of one versus the other?

var MyModule = (function() {

  var _val;

  var api = {
    get value1() {
      return _val
    },
    set value1(value) {
      _val = value
    }
  };

  Object.defineProperty(api, 'value2', {
    get: function() {
      return _val;
    },
    set: function(value) {
      _val = value
    }
  });
  return api;

}());

https://plnkr.co/edit/TbJSD4noZTew8II83eTH?p=preview


Solution

  • Using getter syntax you create a property which, prior to ES2015, you had to know the name of at the time that you were writing the code.

    Object.defineProperty allows you to perform the same as the above but, even before ES2015, does not require you to know the name of the property in advanced. It also allows you to decide if the property is configurable, enumerable, or writable which is not possible using the get/set syntax.

    To answer your exact question: neither is better. They're for different situations. The get/set syntax is simpler to read and write but isn't as powerful as Object.defineProperty.