在本周的学习中我学习了有关ES6和JS高级的相关知识,我在学习ES6的箭头函数遇到的一点问题。在起初,我认为箭头函数的应用实在是复杂难懂,甚至认为它的存在不合理,有点繁琐。但直到当前阶段就发现真香了,在原来可能需要用普通函数十几行的代码,但在箭头函数中可能一两行就可以完成了,大大的减少了代码的书写难度,但需要写好代码还是需要稳扎稳打的基础,所以在接下来一周的ES6和JS高级学习中更应该注重理论和实践的相互结合。
在本周还参加了蓝桥杯的考试——尝到了300块钱的午餐;
<!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>
<style>
div{
width: 200px;
height: 200px;
background: #e3c4b5;
text-align: center;
cursor: pointer;
}
</style>
<body>
<div id="box">我是一个盒子</div>
</body>
<script>
//案例1
const box = document.querySelector('#box');
box.addEventListener('click',function(){
console.log(111);
setTimeout(() => {
this.style.background = "pink";
console.log(this);
}, 1000);
let self = this;
setTimeout(function(){
console.log(self);// this : window //self : box
self.style.background = 'green'
},2000)
})
//案例2 筛选偶数
const arr = [12,34,56,98,23,4,56,7,43];
//箭头函数
const result = arr.filter((item)=> item%2===0)
console.log(result);
</script>
</html>
原本样式 一秒后 两秒后
//箭头函数的形参
//通常使用剩余参数
let num = (...arr) =>{
let sum = 0;
for (let i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
console.log(num(1,2,3,4,5,6,7,8,9));
function nothing1 (){
console.log(this);
}
nothing1();//window; ===window.nothing1();
//箭头函数
let nothing2 = () =>{
console.log(this);
}
nothing2();//window
//对象方法中的普通函数this指向
const obj = {
name : 'zhangsan',
sayHi : function(){
console.log(this);
}
}
obj.sayHi();//{name: 'zhangsan', sayHi: ƒ} 指向obj
//对象方法中的箭头函数this指向
const obj1 = {
name : 'lishi',
sayHello : () =>{
console.log(this);
}
}
obj1.sayHello();//window
//扩展
const obj2 = {
name : 'wangwu',
sayHehe : function (){
let num = 2;
const count = () => {
console.log(this);
}
count();
}
}
obj2.sayHehe();
//{name: 'wangwu', sayHehe: ƒ} this指向obj;
在箭头函数的this属性中
需注意:箭头函数不会创建自己的this,他只会沿用其作用域链的上一层的this;在开发中[使用箭头函数前需要考虑函数中this的值],事件回调函数使用箭头函数时,this为全局的window,因此DOM事件回调函数为了简便,还是不太推荐使用箭头函数;
前端学习的49天