gpt4 book ai didi

JavaScript - 处理 'this' 指针和自定义参数的最佳方法

转载 作者:行者123 更新时间:2023-11-28 17:34:20 24 4
gpt4 key购买 nike

我有一个函数,可以创建一个按钮并向其添加一个事件监听器。在事件监听器函数内处理“this”指针和按钮时存在困惑。

Sample.prototype.myfunc = function my_func() {
this.attra = someValue;
this.attrb = somValueb;

tmpDelNode = this.doc.createElement('span');
tmpDelNode.innerHTML = '<span class="del">X</span>';
this.newAttachmentContainer.appendChild(tmpDelNode.firstChild);
delbtn = this.doc.querySelector('.del');

delbtn.addEventListener('click', function deleteNewAttachment(delbtn) {
delbtn = this.doc.querySelector('.del');
delbtn.previousElementSibling.remove();
delbtn.remove();
this.newAttachments = null;
}.bind(this),
false);
}

在上面的函数中,在 addEventListener 内部,我想保留“this”指针,并且仍然想使用 delbtn。我尝试将“this”指针绑定(bind)到示例,并将 delbtn 作为参数传递。

我想以更精确和最好的方式实现同​​样的目标。实现这一目标的最佳方法是什么?

最佳答案

尝试用括号括住您的函数并给出 delbtn 作为参数 ( bind ):

Sample.prototype.myfunc = function my_func() {
this.attra = someValue;
this.attrb = somValueb;

tmpDelNode = this.doc.createElement('span');
tmpDelNode.innerHTML = '<span class="del">X</span>';
this.newAttachmentContainer.appendChild(tmpDelNode.firstChild);
delbtn = this.doc.querySelector('.del');

delbtn.addEventListener('click', (function deleteNewAttachment(delbtn) {
delbtn.previousElementSibling.remove();
delbtn.remove();
this.newAttachments = null;
}).bind(this, delbtn), false);
}

或者只是在上面声明你的函数(它更漂亮):

function deleteNewAttachment(delbtn) {
delbtn.previousElementSibling.remove();
delbtn.remove();
this.newAttachments = null;
}

Sample.prototype.myfunc = function my_func() {
this.attra = someValue;
this.attrb = somValueb;

tmpDelNode = this.doc.createElement('span');
tmpDelNode.innerHTML = '<span class="del">X</span>';
this.newAttachmentContainer.appendChild(tmpDelNode.firstChild);
delbtn = this.doc.querySelector('.del');

delbtn.addEventListener('click', deleteNewAttachment.bind(this, delbtn), false);
}

关于JavaScript - 处理 'this' 指针和自定义参数的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49487185/

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