我正在使用 Set
维护一堆函数,在调用它一次后,我可以将其从集合中删除。这是我的代码如下:
let onceWrapper = function() {
let args = arguments;
Set.delete(eventName, onceWrapper);
func.apply(this, arguments);
}
Set.add(eventName, onceWrapper.bind(this));
我注意到,当我在 Set.add(eventName, onceWrapper.bind(this));
之后设置断点时行,然后运行 Set.has(onceWrapper)
或Set.has(onceWrapper.bind(this))
在控制台中,它总是返回 false。有什么办法可以解决这个问题吗?我的功能发生变化的原因是什么?无论如何,当我 console.log Set 中的函数时,它返回 [native code]
。谢谢:)
最佳答案
What happens to a function when I do a
bind(this)
?
没什么,原始函数(您调用 bind
的函数)完全不受该调用的影响。但是 bind
返回一个 new 函数(与您调用它的函数不同),该函数在调用时将调用原始函数,确保 this
设置为 bind
的第一个参数。
我应该注意,我不知道您的代码中的 Set
是什么。它显然不是标准的 Set
,因为它没有 static
add
和 has
方法。如果它是标准 Set
的实例,那么当您检查时,至少有两个原因 onceWrapper
不在其中:仅 add
接受单个参数(在我看来这很奇怪,但没关系)。所以 if Set
是 Set
的实例, Set.add(eventName, OnceWrapper.bind(this))
只会添加 eventName
到其中。另一个原因如上所述。
使用名为 things
的普通 Set
,这应该有助于使事情变得更清晰:
function onceWrapper() {
console.log(typeof this);
}
const things = new Set();
const boundOnceWrapper = onceWrapper.bind(this);
things.add(boundOnceWrapper);
// This logs false because each call to `bind` creates a **new** function
things.has(onceWrapper.bind({foo: "bar"}));
// This logs true because we're checking for the same function we added
things.has(boundOnceWrapper);
请注意,即使使用相同的 this
参数调用 bind
时,它也会每次创建一个新函数。它不会内存和重复使用以前的副本。
关于javascript - 当我执行 `bind(this)` 时,函数会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58307587/