gpt4 book ai didi

javascript - 在单击处理程序中正确使用绑定(bind)和引用对象值

转载 作者:行者123 更新时间:2023-12-03 03:44:26 26 4
gpt4 key购买 nike

我无法理解绑定(bind)的正确使用以及对单击处理程序中打开的过去链接的引用。

该函数接收 4 个链接的数组。我只是想点击打开正确的链接。

链接 2 和 3 之所以有效,是因为它们绑定(bind)到了 window 对象。链接 0 和 1 将在传递的第一个数组上工作,但当新的链接数组传递给函数时,单击时,它将打开前一个链接,而不是最近传递给函数的链接。

我知道向窗口对象添加值是不好的做法,因此我一直在尝试找出更好的方法来实现它,同时更好地掌握绑定(bind)、应用和调用。 (如果这里有必要的话)。

为什么传递的前 4 个链接是正确的,但传递任何其他链接时,它将继续引用并打开初始链接集?

links = function(linksArr) {
var that = this;
this.linkArray = linksArr;
//Create an object from array in attempt to get correct link on event click
var linkReference = linksArr.reduce(function(all,item,index){
all[index] = item;
console.log(all);
return all;
},{});
//Does not work. Attempted use of bind
$('.link0').on("click", function () {
window.open(linkReference[0], '_blank');
}.bind(linkReference));
//Does not work. Trying to apply the proper links through the apply method
$('.link1').on("click", function () {
window.open(linksArr[1], '_blank');
}.apply(null,linksArr));
//Works
$('.link2').on("click", function () {
window.open(that.linkArray[2], '_blank');
});
//Works
$('.link3').on("click", function () {
window.open(that.linkArray[3], '_blank');
});
};`

最佳答案

bind() 使您绑定(bind)的元素成为方法内的“this”。您应该使用“this”作为引用,而不是绑定(bind)时使用的名称。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

关于javascript - 在单击处理程序中正确使用绑定(bind)和引用对象值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45469160/

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