变量的解构赋值
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>03_变量的解构赋值</title>
</head>
<body>
<!--
1. 理解:
* 从对象或数组中提取数据, 并赋值给变量(多个)
2. 对象的解构赋值
let {n, a} = {n:'tom', a:12}
3. 数组的解构赋值
let [a,b] = [1, 'atguigu'];
4. 用途
* 给多个形参赋值
-->
<script type="text/javascript">
let obj = {name : 'kobe', age : 39};
// let name = obj.name;
// let age = obj.age;
// console.log(name, age);
//对象的解构赋值
let {age} = obj;
console.log(age);
// let {name, age} = {name : 'kobe', age : 39};
// console.log(name, age);
//3. 数组的解构赋值 不经常用
let arr = ['abc', 23, true];
let [a, b, c, d] = arr;
console.log(a, b, c, d);
//console.log(e);
function person(p) {//不用解构赋值
console.log(p.name, p.age);
}
person(obj);
function person1({name, age}) {
console.log(name, age);
}
person1(obj);
</script>
</body>
</html>
箭头函数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>06_箭头函数</title>
</head>
<body>
<button id="btn">测试箭头函数this_1</button>
<button id="btn2">测试箭头函数this_2</button>
<!--
* 作用: 定义匿名函数
* 基本语法:
* 没有参数: () => console.log('xxxx')
* 一个参数: i => i+2
* 大于一个参数: (i,j) => i+j
* 函数体不用大括号: 默认返回结果
* 函数体如果有多个语句, 需要用{}包围,若有需要返回的内容,需要手动返回
* 使用场景: 多用来定义回调函数
* 箭头函数的特点:
1、简洁
2、箭头函数没有自己的this,箭头函数的this不是调用的时候决定的,而是在定义的时候处在的对象就是它的this
3、扩展理解: 箭头函数的this看外层的是否有函数,
如果有,外层函数的this就是内部箭头函数的this,
如果没有,则this是window。
-->
<script type="text/javascript">
let fun = function () {
console.log('fun()');
};
fun();
//没有形参,并且函数体只有一条语句
let fun1 = () => console.log('fun1()');
fun1();
console.log(fun1());
//一个形参,并且函数体只有一条语句
let fun2 = x => x;
console.log(fun2(5));
//形参是一个以上
let fun3 = (x, y) => x + y;
console.log(fun3(25, 39));//64
//函数体有多条语句
let fun4 = (x, y) => {
console.log(x, y);
return x + y;
};
console.log(fun4(34, 48));//82
setTimeout(() => {
console.log(this);
},1000)
let btn = document.getElementById('btn');
//没有箭头函数
btn.onclick = function () {
console.log(this);//btn
};
//箭头函数
let btn2 = document.getElementById('btn2');
let obj = {
name : 'kobe',
age : 39,
getName : () => {
btn2.onclick = () => {
console.log(this);//obj
};
}
};
obj.getName();
function Person() {
this.obj = {
showThis : () => {
console.log(this);
}
}
}
let fun5 = new Person();
fun5.obj.showThis();
</script>
</body>
</html>
<script>
// 什么时候使用箭头,当一个函数作为另外一个函数的参数的时候
// setTimeout(function () {
// console.log(this);//window
// }, 1000)
//
// setTimeout(() => {
// console.log(this);//window
// }, 1000)
// 问题: 箭头函数中的this是如何查找的了?
// 答案: 向外层作用域中, 一层层查找this, 直到有this的定义.
// const obj = {
// aaa() {
// setTimeout(function () {
// console.log(this); // window
// })
//
// setTimeout(() => {
// console.log(this); // obj对象
// })
// }
// }
//
// obj.aaa()
const obj = {
aaa() {
setTimeout(function () {
setTimeout(function () {
console.log(this); // window
})
setTimeout(() => {
console.log(this); // window
})
})
setTimeout(() => {
setTimeout(function () {
console.log(this); // window
})
setTimeout(() => {
console.log(this); // obj
})
})
}
}
obj.aaa()
</script>