My attempt:
class SetOnceDict extends Function {
constructor() {
super('key', 'return this.get(key);')
}
items = {}
add(key, value) {
if (!this.items.hasOwnProperty(key)) {
this.items[key] = value;
} else {
throw new Error(`Duplicate key ${key}`);
}
}
get(key) {
return this.items[key];
}
}
let dict = new SetOnceDict();
dict.add('one', 'foo');
dict.add('two', 'bar');
console.log(dict.items);
console.log(dict('one'));
I'd expect this to log
{ one: 'foo', two: 'bar' }
foo
instead it errors
return this.get(key);
^
TypeError: this.get is not a function
This works:
console.log(dict.bind(dict)('one'));
But why would it have to be bound to itself when it should already have those properties?
Surprisingly (?) neither super.bind(this);
nor this.bind(this);
in the constructor fix the problem.
How can I make an extension of function using ES6+ class syntax that has custom behaviour when called?