zoukankan      html  css  js  c++  java
  • 前端笔记(关于箭头函数与普通函数的区别的理解)

    大家都知道箭头函数es6新增的函数声明方式,当然普通函数还是可以继续使用的。我以前一直只知道箭头函数只对this指向有影响,但是没法说清楚具体有哪些影响,因此今天来总结整理一下。

    1.普通函数的this指向当前调用者对象箭头函数的this指向其上下文

    let obj={
        a:function(){
            console.log(this)//当前调用者
        },
        b:()=>{
            console.log(this)//上下文
        }
    }
    obj.a()
    obj.b()

    2.箭头函数不能作为构造函数,所以也不能new,new就会报错。普通函数可以

    3.箭头函数不能使用arguments,但可以使用...rest代替。rest参数也能在普通函数中使用,用于函数中传递不定参数

    arguments是类数组,需要遍历进行使用。arguments和rest都必须写在最后面

    const A=(...a)=>{
        console.log(a)
    }
    A(1,2,3,4)//数组
    
    const B=function(){
        console.log(arguments)
    }
    B(1,2,3,4)//类数组

    4.箭头函数没有原型对象,普通函数有

    //原型区别
    const F=()=>{}
    const G=function(){}
    console.log(F.prototype)//undefined
    console.log(G.prototype)//原型对象

    拓展知识:

    1.call、apply、bind可以改变普通函数this指向

    此处使用call后this就不是参数1的对象了,然后自动调用f函数。

    apply:参数2传的是数组。bind:重新绑定对象,生成新的函数,需要重新调用

    //改变this指向
    const f=function(a){
        console.log(this.name+a)
    }
    f()//undefined
    f.call({name:1},2)//3

    2.箭头函数无法改变this指向,这个this还是代表上下文,不是那个对象

    const F=()=>{
        console.log(this)
    }
    F.call({a:1})//window
  • 相关阅读:
    POJ 1045
    POJ 1051
    POJ 1047
    POJ 1050
    POJ 1046
    POJ 1036
    POJ 1035
    POJ 1032
    【洛谷P1412】经营与开发
    【洛谷P3377】【模板】左偏树(可并堆)
  • 原文地址:https://www.cnblogs.com/wuhairui/p/12818905.html
Copyright © 2011-2022 走看看