Reputation: 805
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
Upvotes: 6
Views: 1947
Reputation: 7361
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().
Upvotes: 0
Reputation: 1055
As mentioned in documentation.
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.
Upvotes: 0
Reputation: 32511
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
.
Upvotes: 5