- function global(){
- console.log(this);//widnow
- }
- global()
- const global = () =>{
- console.log(this);//widnow
- }
- global()
- 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
- 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 是静态的一旦定义了就无法改变
当你要传多个参数的时候
...可以获得全部参数 nums是自定义的名
- function demo(...nums){
- console.log(nums);//获取数组[1,2,3,4]
- console.log(...nums);//获取数字1,2,3,4 被称为解构数组
- }
- demo(1,2,3,4)
...可以获得全部参数 info是自定义的名
- function connect({name,...info}){
- console.log(name);//张三
- console.log(info);//输出对象 {password:"1234456",port:"45423"}
- }
- connect({name:"张三",password:"1234456",port:"45423"})
- const arr = [1,2,3,4];
- console.log(...arr);
- const arr1 = [1,2,3,4];
- const arr2 = [5,6,7,8];
- console.log(...arr1,...arr2);
- const arr1 = [1,2,3];
- const arr2 = [...arr1];
- console.log(arr2);