ES6:箭头函数
一、箭头函数
(一)标准写法
<script>
const fn = () => {
console.log(123);
};
fn();
</script>
(二)方法执行体单行
<script>
const sum = (a, b) => a + b;
// 3
console.log(sum(1, 2));
</script>
(三)单个形参
一个参数省略形参小括号
<script>
const fn = v => {
console.log(v);
};
// 123
fn(123);
</script>
二、可变参数函数
<script>
const sum = (...args) => {
let total = 0;
args.forEach(item => total += item);
return total;
};
console.log(sum(1, 2, 3, 4));
</script>
三、箭头函数this指向
- 函数体内的this对象,是定义时所在的对象不是使用时所在的对象
- 即使是call,apply,bind等方法也不能改变箭头函数this的指向
(一)坑
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button id="normal">普通函数</button>
<button id="arrow">箭头函数</button>
<script>
window.onload = function () {
document.querySelector('#normal').addEventListener('click', function () {
// <button id="normal">普通函数</button>
console.log(this);
});
document.querySelector('#arrow').addEventListener('click', () => {
// Window {parent: Window, opener: null, top: Window, length: 0, frames: Window, …}
console.log(this);
});
};
</script>
</body>
</html>