admin管理员组文章数量:1289483
After years of using JavaScript I met an error that I had never seen.
I wanted to calculate the intersection between two Sets, so I wrote:
let a = new Set([1, 2, 3]);
let b = new Set([2, 3, 4]);
let intersection = [...a].filter(x => b.has(x));
console.log(intersection);
After years of using JavaScript I met an error that I had never seen.
I wanted to calculate the intersection between two Sets, so I wrote:
let a = new Set([1, 2, 3]);
let b = new Set([2, 3, 4]);
let intersection = [...a].filter(x => b.has(x));
console.log(intersection);
And it works, but I noticed that I can shorten the above code. Since the filter method just wants a function and invokes it no matter how it is defined, and I wrote:
let a = new Set([1, 2, 3]);
let b = new Set([2, 3, 4]);
let intersection = [...a].filter(b.has);
console.log(intersection);
And in this case, unexpectedly, I receive the following error:
Uncaught TypeError: Method Set.prototype.has called on inpatible receiver undefined
I also noticed that this doesn't happen if I bind Set.prototype.add
to the variable:
let a = new Set([1, 2, 3]);
let b = new Set([2, 3, 4]);
let intersection = [...a].filter(Set.prototype.bind(b));
console.log(intersection);
My question is: why does it happen? Why b.has
is not a valid callback?
- Does this answer your question? Method Set.prototype.add called on inpatible receiver undefined – ggorlen Commented Mar 7, 2022 at 3:25
2 Answers
Reset to default 7has
method loses internal this
context when you pass it as a callback.
That is the reason it works when you use bind
to provide it right context.
For more info it has been documented here
You can use the Array#filter
function and pass thisArg
as the second parameter. So the has
will take this second parameter as it's this
, and proceeds to evaluate or pare.
Here's an example:
function pare(a, b) {
return [...a].filter(Set.prototype.has, b);
}
let a = new Set([1, 2, 3]);
let b = new Set([2, 3, 4]);
console.log(pare(a, b));
Another idea:
function pare(a, b) {
return new Set([...a].filter(Set.prototype.has, b));
}
let a = new Set([1, 2, 3]);
let b = new Set([2, 3, 4]);
console.log([...pare(a, b).values()]);
本文标签: javascriptMethod Setprototypehas called on incompatible receiver undefinedStack Overflow
版权声明:本文标题:javascript - Method Set.prototype.has called on incompatible receiver undefined - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741480292a2381128.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论