箭头函数
- 箭头函数表达式的语法比函数表达式更简洁,并且没有自己的this,arguments,super或new.target
- 箭头函数表达式更适用于那些本来需要匿名函数的地方,并且它不能用作构造函数。
- 箭头函数 this 是静态的 始终 指向函数声明所在作用域下的this的值
<script>
let fn = (a, b) => {
return a + b
}
let aa = fn(1, 2)
console.log(aa);
// 箭头函数 this 是静态的 始终 指向函数声明所在作用域下的this的值
function getName() {
console.log(this.name);
}
let getName2 = () => {
console.log(this.name);
}
window.name = '箭头函数'
const hanshu = {
name: "J箭tou"
}
// 直接调用
getName()
getName2()
// call 方法调用
getName.call(hanshu) // J箭tou
getName2.call(hanshu) //箭头函数
// 不能作为构造函数实例化对象
// 不能使用 arguments 变量
// let fn = () => {
// console.log(arguments);
// }
// fun(1, 2) // 报错
// 箭头函数的简写
// 省略小括号 当形参有且只有一个的时候
let add = n => { // n 省略小括号
return n + n
}
console.log(add(9));
// 省略花括号
// 当代码体 只有一条语句的时候 return 必须省略
// 语句执行结果就是函数返回值
let p = n => n * n
console.log(p(9));
</script>
</body>
@H_502_25@
箭头函数 实践
<style>
.ad {
width: 100px;
height: 100px;
background-color: greenyellow;
}
</style>
</head>
<body>
<div class="ad"></div>
<script>
// // 需求 点击div 变颜色
// // 1获取元素
// let add = document.querySelector('.ad')
// // 2绑定事件
// add.addEventListener('click', function () {
// let _this = this // 保存this值
// // console.log(this);
// // 添加定时器
// setTimeout(function () {
// // console.log(this); //指向的是window
// // 修改背景颜色
// _this.style.background = 'pink'
// }, 2000) //2秒后执行
// });
// 箭头函数
// 需求 点击div 变颜色
// 1获取元素
let add = document.querySelector('.ad')
// 2绑定事件
add.addEventListener('click', function () {
let _this = this // 保存this值
// console.log(this);
// 添加定时器
setTimeout(() => {
// console.log(this); //指向的是window
// 修改背景颜色
// 箭头函数 this 是静态的 始终 指向函数声明所在作用域下的this的值
// add 声明 的所以指向的是add
this.style.background = 'pink'
}, 2000) //2秒后执行
});
// 从数组中返回偶数的元素
let arr = [2, 4, 8, 6, 9, 5,]
// filter() 方法创建一个新的数组,
// 新数组中的元素是通过检查指定数组中符合条件的所有元素。
// let newArr = arr.filter(function (items) {
// if (items % 2 === 0) {
// return true
// } else {
// return false
// }
// })
// console.log(newArr);
// 1.
// let newArr = arr.filter(items => {
// if (items % 2 === 0) {
// return true
// } else {
// return false
// }
// })
// console.log(newArr);
// 2.
let newArr = arr.filter(items => items % 2 === 0)
console.log(newArr);
</script>
</body>
@H_502_25@
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。