This is a question about how JavaScript getters and setters work.
Mozilla's implementation of log4j as a JavaScript module (partial implementation, just the important parts needed for the intended use cases such as in Firefox Sync) contains the following getter/setter definition.
What does the 'delete' in the getter/setter do for you? What does that even mean? It seems to have the effect of making the first use have different results from following uses (but if so, how)?
get repository() {
delete Log4Moz.repository;
Log4Moz.repository = new LoggerRepository();
return Log4Moz.repository;
},
set repository(value) {
delete Log4Moz.repository;
Log4Moz.repository = value;
},
The simplest way to avoid setters is to hand the values to the constructor method when you new up the object. This is also the usual pattern when you want to make an object immutable.
You may use lombok - to manually avoid getter and setter method. But it create by itself. The using of lombok significantly reduces a lot number of code.
The interface specifies that the property should at least have a public setter. The definition and accessibility of the getter is left to the implementing class. So if the interface contract only needs to write, get can be left open.
Getters and setters allow us to define Object Accessors. The difference between them is that the former is used to get the property from the object whereas the latter is used to set a property in an object.
FROM MDN:
The delete operator deletes a property of an object.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete
The question (and existing answers) are missing an important piece of context; the getter and setter are defined on the Log4Moz object. With that in mind, what happens when either the getter or setter is called and it deletes the property for which it is defined?
delete
on accessor properties (properties with get/set) has the same effect as it does on data properties, namely that it removes the property. After executing delete Log4Moz.repository
, the repository
property is no longer present on the Log4Moz
object and the getter/setter functions are no longer bound to that property.
The next lines, which assign to Log4Moz.repository
behave as you would expect. A data property is created in the Log4Moz
object with the given value.
In effect, what this does is replace an accessor property with a data property after the first access (either get or set), making a lazily-initialized data property.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With