<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<input type="button" value="按钮" />
<script>
// 箭头函数使用过程中的总结:
// 1) 语法: () => {}
// 2) 箭头函数中的第一个() 就是用来设置形参, {} 实现功能
// let fn = (a, b, ...c) => {
// console.log(a, b, c);
// }
// fn(123, 456, 789, 666, 888, 999);
// 3) 箭头函数是否可以设置返回值? 可以设置返回值
// let fn = () => {
// return 'abc';
// }
// let res = fn();
// console.log(res);
// 回顾this指向:
// ☞ 普通函数中的this永远都指向window
// ☞ 方法中的this永远都指向方法的调用对象
// ☞ 事件中的this永远都指向事件源
// ☞ 构造函数中的this指向的是实例对象
// =============== 箭头函数特有的 ===================
// a) 箭头函数中的this没有固定的指向
// 箭头函数中的this指向其父级作用域中的this
// 父级作用域中: 全局作用域中的this指向的是window
console.log(this)
let fn = () => {
//局部作用域
console.log(this)
}
fn()
let btn = document.querySelector('input')
btn.onclick = () => {
// 局部作用域
console.log(this)
}
let btn = document.querySelector('input')
btn.onclick = function () {
//this: 指向当前事件源(btn按钮标签对象)
let obj = {
eat: () => {
// 局部作用域
console.log(this)
//this: 指向当前事件源(btn按钮标签对象)
}
}
obj.eat()
}
let btn = document.querySelector('input')
btn.onclick = () => {
// this ===> window
console.log('点击', this)
let obj = {
eat: () => {
// 局部作用域
console.log(this)
// this ===> window
}
}
obj.eat()
}
</script>
</body>
</html>
this指向,箭头函数中的this指向问题详细解读
于 2022-03-27 10:05:27 首次发布