One of the main reason the getter and setter feature was implemented was to close a feature gap that required people to hack a js interpreter/browser to achieve one feature that browsers could do:
element.innerHTML = "<div> some HTML string </dif>";
Now, innerHTML
may look like a property but it actually behaves more like a function. It's actually an HTML compiler.
You can see this by trying to do:
element.innerHTML += "<table>";
element.innerHTML += "<tr><td>test</td></tr>"; // does not work
This is because the first "call" to innerHTML
compiles the html to:
<table></table>
The second line will fail because <tr>
outside of a table is invalid HTML.
With getter and setter you can finally implement a feature like this in pure javascript - make property access trigger a function call.
Of course, innerHTML
is just one example of getters and setters and a very bad example of an API at that. It's up to your creativity what you can actually do with getters and setters.
Now, for my personal opinion (and it's only my opinion so take it for what it's worth): I think innerHTML
provides a good example for why getter and setters should not normally be used. The confusion over <table>
is one good example of breaking user's expectation. If innerHTML
was implemented as element.appendHTML()
it's behavior would be less surprising. As a programmer I'd be very surprised if a property access does something I don't expect.
That said, I am glad that getters and setters exist to make language library features self-implementable without needing to resort to hacking in C/C++.