简体   繁体   中英

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

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 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.

FROM MDN:

The delete operator deletes a property of an object.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete

delete operator deletes a property of an object. if you have a object

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

and you do

delete oa;

your object will look like this

o = {b : "world" };

and after that if you do

oa = "foo";

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM