结论:
在标准函数中,this 引用的是把函数当成方法调用的上下文对象。
在箭头函数中, this引用的是定义箭头函数的上下文。
举例说明:
<!-- html -->
<button> 点击 </button>
// Js中:(使用了jquery的语法)
// 1. 此时 button调用了后面的函数,所以this指向button.
$('button').click(function(){
console.log(this)
})
// 2. 此时,在网页的全局中调用函数,所以this指向windows
$('button').click(function(){
func()
})
function func(){
console.log(this)
}
// 3. 此时,定义箭头函数的上下文为windows,所以this指向windows
$('button').click(function(){
ArrowFunc()
})
var ArrowFunc = ()=>{
console.log(this)
}
// 4. 此时,定义箭头函数的上下文在button的点击事件中,所以this指向button
$('button').click(function(){
var ArrowFunc =()=>{
console.log(this)
}
ArrowFunc()
})
实际开发中的应用:
如果想让某个函数中的this指向特定元素,那么可以在该元素的事件(如点击事件)中使用箭头函数。
(本文为原创,转载请告知,欢迎留言讨论)