I have extended class from Map
:
class ModifiedMap extends Map {
constructor(arg) {
super(arg);
}
set(key, value) {
console.log("doing some work here")
}
}
And if I try to create ModifiedMap
, I see "doing some work here" printing n
times (depends on iterator).
new ModifiedMap([["a", "apple"],["b", "orange"],["c", "banana"]])
How can I avoid using my subclass’s set
method in the internal algorithm of constructing Map
? Sure I could rename from set to any name, but I want to know is it possible use the same name?
2
Answers
You could use a flag to tell your subclass
set
whether the instance construction is complete, then check that flag inset
. If the flag isn’t set, pass the call on tosuper.set
:That said, it seems fairly odd to bypass your subclass’s customized
set
only during construction. A separate method specific to the subclass may be a better idea.A variation of @T.J.Crowder’s solution is to add the flag to the overriden method. Internal calls will not provide this flag, but your custom calls can pass it conditionally.