this 和箭头函数
ES6 中引入了箭头函数,作为编写 JavaScript 函数的新语法。由于其语法简洁,它鼓励使用短小的函数,从而使代码看起来更简洁(也() =>
更酷炫😄)。
作为一个刚刚开始理解 ES6 语法的初学者,我开始到处使用箭头函数,但并没有真正理解它们的工作原理。正如你所料,我最终遇到了一些问题,尤其是在使用this
关键字时。
this
有时会有点令人困惑,因为它的值会根据函数的执行上下文以及模式(严格或非严格)而变化。关于它的细节已经有很多文章,所以我只关注一件事:
this
箭头函数如何工作
在常规函数中,this
当定义为对象的方法时,引用该对象。因此,我们可以这样做:
const brunch = {
food: 'Dim sum',
beverage: 'Jasmine tea',
order: function() {
return `I'll have the ${this.food} with ${this.beverage} please.`
}
}
调用brunch.order()
将会返回"I'll have the Dim sum with Jasmine tea please."
让我们编辑它并使用箭头函数order:
:
const brunch = {
food: 'Dim sum',
beverage: 'Jasmine tea',
order: () => {
return `I'll have the ${this.food} with ${this.beverage} please.`
}
}
这次,调用brunch.order()
将返回"I'll have the undefined with undefined please."
Boththis.food
并this.beverage
返回undefined
。
它与普通函数配合使用,那么发生了什么?在普通函数中,this
是我们的order
对象。当使用箭头函数时,this
不绑定任何内容,它只是从父作用域(在本例中是窗口)继承。在箭头函数的console.log(this)
之前添加 ,会返回一个对象,因此它会查找 和,而这显然都是。return
Window
Window.food
Window.beverage
undefined
因此,箭头函数不适合作为对象方法。
另一个常见问题是事件处理程序。以下是一个例子:
// change button colour on click
<style>
.on {background: red;}
</style>
<button id="click">Toggle</button>
<script>
const button = document.querySelector('#click');
button.addEventListener('click', function() {
console.log(this); // button
this.classList.toggle('on');
});
</script>
在上面的代码中,this
指的是按钮。点击按钮会按预期切换颜色。将函数更改为箭头函数:
// change button colour on click
<style>
.on {background: red;}
</style>
<button id="click">Toggle</button>
<script>
const button = document.querySelector('#click');
button.addEventListener('click', () => {
console.log(this); // Window { ... }
this.classList.toggle('on');
});
</script>
并this
成为浏览器的window
属性。点击按钮会报错TypeError
。如果您依赖this
事件处理器,则可能需要常规函数。
因此,尽管箭头函数可能很酷很流行,但最好还是了解它们的工作原理,并知道何时使用它们以及何时不使用它们。
鏂囩珷鏉ユ簮锛�https://dev.to/wangonya/this-and-arrow-functions-a67