Using delete in JavaScript getter / setter to delete getter / setter

This is a question about how JavaScript getters and setters work.

Mozilla's implementation of log4j as a JavaScript module (partial implementation, only important parts needed for intended use cases, like Firefox Sync) contains the following getter / setter definition.

What does 'delete' in getter / setter do for you? What does this even mean? Apparently the effect of the first use has different results from the 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;
},

      

+3


source to share


3 answers


The question (and existing answers) lacks important context; getter and setter are defined in the Log4Moz object. With this in mind, what happens when either the getter or the setter is called and it removes the property for which it is defined?

delete

on accessor properties (properties with get / set) has the same effect as data properties, namely that it removes the property. Once executed, the delete Log4Moz.repository

property is repository

no longer present on the object Log4Moz

, and the getter / setter functions are no longer bound to that property.



The following lines, which are assigned Log4Moz.repository

, behave as you expected. The data property is created on the object Log4Moz

with the given value.

What this really means is that instead of the accessor property after the first access (either get or set), replace the accessor property with a data property, creating a lazy-initialized data property.

+2


source


FROM MDN:

The delete operator deletes a property on an object.



https://developer.mozilla.org/en/JavaScript/Reference/Operators/delete

+1


source


Delete operator

removes a property of an object. if you have an object

o = {a: "hello", b: "world"};

and you do

remove oa;

your object will look like this

o = {b: "world"};

and after that if you do

oa = "foo";

it will add a new property a to object o and assign the value "foo" to it and your object will be like

o = {a: "foo", b: "world"};

0


source







All Articles