Suppose I've a Set
as a lookup table.
const myset = new Set(["key1", "key2", "key3", "keepMe"]);
I wanted to filter another array of some other keys (say mykeys
) which are in myset
.
const mykeys = ["ignoreMe", "keepMe", "ignoreMeToo", "key2"];
Question:
Why do I have to use
const filtered = mykeys.filter(k => myset.has(k))
instead of
const filtered = mykeys.filter(myset.has)
// TypeError: Method Set.prototype.has called on incompatible receiver undefined
i.e., why do I've to create an anonymous lambda function in filter? keys.has
has same signature (argument - element, return boolean). A friend told me it's related to this
.
Whereas mykeys.map(console.log)
works without error (although not being of much use).
I came across this article at MDN and I still don't get why "'myset' is not captured as this". I understand the workaround but not the "why". Can anyone explain it with some details and references in a human friendly way?
Update: Thank you all for the responses. Maybe I wasn't clear about what I'm asking. I do understand the workarounds.
@charlietfl understood. Here's his comment, the thing I was looking for:
Because filter() has no implicit
this
where asset.has
needs to have properthis
context. Calling it inside anonymous function and manually adding argument makes the call self contained.