箭头函数是什么
1. 认识箭头函数
2. 箭头函数的结构
- const/let 函数名 = 参数 => 函数体。
3. 如何将一般函数改写成箭头函数
// 3.如何将一般函数改写成箭头函数
// 一般函数形式
function add() {}
// 箭头函数形式
const add = () => {};
箭头函数的注意事项
1. 单个参数
2. 单行函数体
3. 单行对象
this 指向
1. 全局作用域中的 this 指向
2. 一般函数(非箭头函数)中的 this 指向
- 只有在函数调用的时候 this 指向才确定,不调用的时候,不知道指向谁。
- this 指向和函数在哪儿调用没关系,只和谁在调用有关。
- 没有具体调用对象的话,this 指向 undefined,在非严格模式下,转向 window,默认是非严格模式。
3. 箭头函数中的 this 指向
不适用箭头函数的场景
1. 作为构造函数
2. 需要 this 指向调用对象的时候
3. 需要使用 arguments 的时候
箭头函数的应用
- 使用一般函数需要使用that=this,对当前的this对象进行保存。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>模板字符串的应用</title>
<style>
body {
padding: 50px 0 0 250px;
font-size: 30px;
}
#btn {
width: 100px;
height: 100px;
margin-right: 20px;
font-size: 30px;
cursor: pointer;
}
</style>
</head>
<body>
<button id="btn">开始</button>
<span id="result">0</span>
<script>
const btn = document.getElementById('btn');
const result = document.getElementById('result');
const timer = {
time: 0,
start: function () {
let that = this;
btn.addEventListener(
'click',
function () {
setInterval(function () {
that.time++;
result.innerHTML = that.time;
}, 1000);
},
false
);
}
};
timer.start();
</script>
</body>
</html>
- 使用箭头函数,由于箭头函数没有this会自动向外层逐级查找,这样可以剩去that=this操作。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>模板字符串的应用</title>
<style>
body {
padding: 50px 0 0 250px;
font-size: 30px;
}
#btn {
width: 100px;
height: 100px;
margin-right: 20px;
font-size: 30px;
cursor: pointer;
}
</style>
</head>
<body>
<button id="btn">开始</button>
<span id="result">0</span>
<script>
const btn = document.getElementById('btn');
const result = document.getElementById('result');
const timer = {
time: 0,
start: function () {
btn.addEventListener(
'click',
() => {
setInterval(() => {
this.time++;
result.innerHTML = this.time;
}, 1000);
},
false
);
}
};
timer.start();
</script>
</body>
</html>