javascript - 当我执行 `bind(this)` 时,函数会发生什么?

标签 javascript

我正在使用 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 addhas 方法。如果它是标准 Set实例,那么当您检查时,至少有两个原因 onceWrapper 不在其中:仅 add接受单个参数(在我看来这很奇怪,但没关系)。所以 if SetSet 的实例, 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/

相关文章:

javascript - promise 的 Node 模式

使用下拉列表运行的 Javascript 函数

javascript - 将 JavaScript requestAnimFrame 移植到 TypeScript

javascript - 不存在 'Access-Control-Allow-Origin' header 。 origin因此不允许访问

javascript - 如何在javascript中有条件地在对象内创建成员?

java - 通过javascript在java中设置一个 boolean 标志

javascript - 在 javascript 中对大量文本运行复杂查找/替换的最有效方法?

javascript - 我想通过使用参数访问数组的值

javascript - 我的代码中的 ${a} 和 => 是什么?

javascript - ng-style 的变化对 CSS-Style 没有影响