• ES6-箭头函数-this指向-rest参数(三点运算符)


    箭头函数

    1.全局作用域下 this 语句

    1.普通函数

    1. function global(){
    2. console.log(this);//widnow
    3. }
    4. global()

    2.箭头函数

    1. const global = () =>{
    2. console.log(this);//widnow
    3. }
    4. global()

    2.对象里面的this指向

    1.普通函数

    1. function person(realname,age){
    2. this.realname = realname;
    3. this.age = age;
    4. this.say = function(){
    5. console.log(this);
    6. }
    7. }
    8. const p1 = new person('张三',19);//'张三',19
    9. p1.say();
    10. const p2 = new person('李四',20);//'李四',20
    11. p2.say();

     普通函数可以被 call 更改 this 指向

     p2.say.call(p1);//'张三',19

    2.箭头函数

    1. function person(realname,age){
    2. this.realname = realname;
    3. this.age = age;
    4. this.say = ()=>{
    5. console.log(this);
    6. }
    7. }
    8. const p1 = new person('张三',19);//'张三',19
    9. p1.say();
    10. const p2 = new person('李四',20);//'李四',20
    11. // p2.say();

     call 更改不了箭头函数的 this 指向

      p2.say.call(p1);//'李四',20  

    总结:普通函数和箭头函数 this 区别
                1.普通函数 this 与调用者有关,调用者是谁就是谁
                2.箭头函数的 this 与当时定义的上下文的 this 有关,this 是静态的一旦定义了就无法改变

    1.rest 参数    三点运算符

    当你要传多个参数的时候

    ...可以获得全部参数  nums是自定义的名

    1. function demo(...nums){
    2. console.log(nums);//获取数组[1,2,3,4]
    3. console.log(...nums);//获取数字1,2,3,4 被称为解构数组
    4. }
    5. demo(1,2,3,4)

    2.rest 参数   对象   要记住添加大括号 {}

    ...可以获得全部参数  info是自定义的名

    1. function connect({name,...info}){
    2. console.log(name);//张三
    3. console.log(info);//输出对象 {password:"1234456",port:"45423"}
    4. }
    5. connect({name:"张三",password:"1234456",port:"45423"})

    3.rest 参数   数组

    1. const arr = [1,2,3,4];
    2. console.log(...arr);

    4.rest 参数  合并两个数组

    1. const arr1 = [1,2,3,4];
    2. const arr2 = [5,6,7,8];
    3. console.log(...arr1,...arr2);

    5.rest 参数   复制数组

    1. const arr1 = [1,2,3];
    2. const arr2 = [...arr1];
    3. console.log(arr2);

  • 相关阅读:
    shell编程100例,查缺补漏
    二项分布以及实现
    深入Spring 5 事务原理与源码分析【精品分享】
    CMMI是什么意思
    利用userfaultfd + setxattr堆占位
    ClickHouse(18)ClickHouse集成ODBC表引擎详细解析
    0 基础 Java 自学之路(5)
    为什么说使用领英的人一定要用领英精灵
    Java语言怎样接入代码demo
    spring的事务传播机制
  • 原文地址:https://blog.csdn.net/m0_70552412/article/details/126830453