箭头函数
1.全局作用域下 this 语句
1.普通函数
function global(){
console.log(this);//widnow
}
global()
2.箭头函数
const global = () =>{
console.log(this);//widnow
}
global()
2.对象里面的this指向
1.普通函数
function person(realname,age){
this.realname = realname;
this.age = age;
this.say = function(){
console.log(this);
}
}
const p1 = new person('张三',19);//'张三',19
p1.say();
const p2 = new person('李四',20);//'李四',20
p2.say();
普通函数可以被 call 更改 this 指向
p2.say.call(p1);//'张三',19
2.箭头函数
function person(realname,age){
this.realname = realname;
this.age = age;
this.say = ()=>{
console.log(this);
}
}
const p1 = new person('张三',19);//'张三',19
p1.say();
const p2 = new person('李四',20);//'李四',20
// p2.say();
call 更改不了箭头函数的 this 指向
p2.say.call(p1);//'李四',20
总结:普通函数和箭头函数 this 区别
1.普通函数 this 与调用者有关,调用者是谁就是谁
2.箭头函数的 this 与当时定义的上下文的 this 有关,this 是静态的一旦定义了就无法改变
1.rest 参数 三点运算符
当你要传多个参数的时候
...可以获得全部参数 nums是自定义的名
function demo(...nums){
console.log(nums);//获取数组[1,2,3,4]
console.log(...nums);//获取数字1,2,3,4 被称为解构数组
}
demo(1,2,3,4)
2.rest 参数 对象 要记住添加大括号 {}
...可以获得全部参数 info是自定义的名
function connect({name,...info}){
console.log(name);//张三
console.log(info);//输出对象 {password:"1234456",port:"45423"}
}
connect({name:"张三",password:"1234456",port:"45423"})
3.rest 参数 数组
const arr = [1,2,3,4];
console.log(...arr);
4.rest 参数 合并两个数组
const arr1 = [1,2,3,4];
const arr2 = [5,6,7,8];
console.log(...arr1,...arr2);
5.rest 参数 复制数组
const arr1 = [1,2,3];
const arr2 = [...arr1];
console.log(arr2);