在使用 JavaScript 多年后,我遇到了一个我从未见过的错误。
我想计算两个Set之间的交集,所以我写道:
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);Run Code Online (Sandbox Code Playgroud)
它有效,但我注意到我可以缩短上面的代码。由于 filter 方法只需要一个函数,不管它是如何定义的都会调用它,所以我写道:
let a = new Set([1, 2, 3]);
let b = new Set([2, 3, 4]);
let intersection = [...a].filter(b.has);
console.log(intersection);Run Code Online (Sandbox Code Playgroud)
在这种情况下,出乎意料的是,我收到以下错误:
未捕获的类型错误:方法 Set.prototype.has 调用了不兼容的接收器未定义
我还注意到,如果我绑定Set.prototype.add到变量,这不会发生:
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);Run Code Online (Sandbox Code Playgroud)
我的问题是:为什么会发生?为什么b.has不是有效的回调?