The MDN documentation for the set
function appears to suggest that a setter defined in [ECMAScript 2015] should not exist in an object literal alongside a data entry for the same property.
[ECMAScript 2015] setter must not appear in an object literal ... with a data entry for the same property.
However, this rule seems to change when employing the super keyword.
class Foo {
constructor(bar){
this.bar = bar
}
set bar(newBar){
if (!newBar.match(/\w+/))
throw Error("Invalid bar value")
// Despite not being a derived class, I can still use 'super'.
return super.bar = newBar
}
}
const baz = new Foo("Baz")
baz.bar = "new value" // No recursion
This feature is advantageous as it eliminates the need to conceal the property by adding an underscore prefix. It also avoids altering the property enumerability to prevent the hidden version from appearing in loops or serialization processes.
Nevertheless, the set
syntax can be somewhat obscure, making it challenging to understand its exact functionality.
Am I violating any rules by utilizing this method, or is it acceptable?
Additionally, what does the usage of super
signify here?