我正在进行JavaScript30挑战,在第3课中,他有一些事件监听器调用引用其所调用的元素的函数作为this
:
const inputs = document.querySelectorAll('.controls input');
function handleUpdate() {
const suffix = this.dataset.sizing || '';
document.documentElement.style.setProperty(`--${this.name}`, this.value + suffix);
}
inputs.forEach(input => input.addEventListener('change', handleUpdate));
inputs.forEach(input => input.addEventListener('mousemove', handleUpdate));
我试图使用ES6箭头函数重写它,但是我无法正确地使this
工作。我使用target
得到了一种解决方法:
const handleUpdate = (e) => {
const that = e.target;
const newValue = `${that.value}${that.dataset.sizing || ''}`;
etc.
}
但我最初尝试绑定函数的方式是这样的:
input.addEventListener('change', handleUpdate.bind(this));
但是函数内部的this
仍然指向window
,我不明白为什么。
在这种情况下,没有“正确”的方法将函数绑定到元素吗?
this
,那么你需要使用常规函数。箭头函数不能很好地与this
协同工作。 - slebetmanthis
,要么使用e.currentTarget
(不是e.target
!!) - Oriol