【发布时间】:2017-12-06 01:36:35
【问题描述】:
我正在经历 JavaScript30 挑战,在 lesson 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中不能正常工作。 -
另外,有什么正确的方法可以用箭头函数来做到这一点吗?不
-
我想我记得读过一些东西,说或建议,Arrow 函数是明确编写的,以避免影响“this”。
-
正常功能和
this或e.currentTarget(不是e.target!!) -
箭头函数只允许从它们定义的环境中继承“this”的值,而不是它们被调用的上下文。演示代码使用常规函数,“this”引用它被调用的环境。根据定义,箭头函数是不可能的,因此为什么不能在任何需要使用“this”的地方使用它们。
标签: javascript this