gpt4 book ai didi

Javascript:绑定(bind)/取消绑定(bind)函数行为

转载 作者:行者123 更新时间:2023-11-30 14:16:29 25 4
gpt4 key购买 nike

当我将函数与传入 thisArg 的父 this 绑定(bind)时,我无法取消绑定(bind)相同的命名函数表达式,但如果没有它,我可以取消绑定(bind)函数本身。这是为什么?

这有效:

choicesList.addEventListener("click", function() {

const self= this;

document.addEventListener("click", function checkClick(e) {

if (!e) e = event;
if (!self.contains(e.target)) {

document.removeEventListener("click", checkClick);
}
}, false);
});

这不会:

choicesList.addEventListener("click", function() {

document.addEventListener("click", function checkClick(e) {

if (!e) e = event;
if (!this.contains(e.target)) {
document.removeEventListener("click", checkClick);
}
}.bind(this), false);
});

最佳答案

出现此问题的原因是调用 bind()函数返回该函数的新实例:

function someHandler() {
alert('hi');
}

const someHandlerBinded = someHandler.bind(document);


// Returns false, seeing as these are different instances of the function
console.log( someHandlerBinded === someHandler );

通过 bind() 的结果直接设置事件处理程序正如您在第二个代码块中一样,这会导致该函数处理程序的新实例被传递到 addEventListener() 。这又意味着随后尝试在线删除此处理程序:

document.removeEventListener("click", checkClick);

将会失败,因为定义的函数checkClick与用于该单击事件的实际处理函数不同(即从 function checkClick(){ ... }.bind() 返回的新函数实例)

解决此问题的一种方法可能如下:

choicesList.addEventListener("click", function() {

// Declare the bound version of the click handler
const boundClickHandler = function checkClick(e) {

if (!e) e = event;

if (!this.contains(e.target)) {

// Removing the result of bind, rather than the declared
// checkClick handler
document.removeEventListener("click", boundClickHandler);
}
}.bind(this)

// Adding the result of bind as you currently are doing
document.addEventListener("click", boundClickHandler, false);
});

关于Javascript:绑定(bind)/取消绑定(bind)函数行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53491770/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com