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

3

6

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

Ist answered 12/1, 2017 at 15:23 Comment(0)
F
5

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.

Fortunna answered 12/1, 2017 at 15:30 Comment(0)
G
0

One "advantage" of Object.defineProperty vs get/set notation is that defineProperty can be used at any time, even on objects that have already been created (on which you cannot use the shorthand 'get' notation). From the mdn:

To append a getter to an existing object later at any time, use Object.defineProperty().

Gruchot answered 12/1, 2017 at 15:33 Comment(0)
A
0

As mentioned in documentation.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty

Normal property addition through assignment creates properties which show up during property enumeration (for...in loop or Object.keys method), whose values may be changed, and which may be deleted. This method allows these extra details to be changed from their defaults. By default, values added using Object.defineProperty() are immutable.

Amiamiable answered 12/1, 2017 at 15:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.