美文网首页
aa.箭头函数

aa.箭头函数

作者: BabyMT | 来源:发表于2020-06-22 16:01 被阅读0次

    1. 是匿名函数,没有名字

    function notArrow (a) {
      return 1
    }       //普通函数有名字
    (a) => {
      return 11
    }      //箭头函数没有名字
    

    2. 不可以用于构造函数,就是new funName()

    var notArrow = function (a) {
      return 1
    }
    var arrow = (a) => {
      return 11
    }
    var notArrow2 = new notArrow()
    var arrow2 =  new arrow()
    

    3. 不具有arguments对象

    var notArrow = function (a) {
      console.log(arguments)
      return 1
    }
    var arrow = (a) => {
      console.log(arguments)
      return 11
    }
    notArrow('aaa','bbb')        //[Arguments] { '0': 'aaa', '1': 'bbb' }
    arrow('aaa','bbb')
    

    ps:若想要获取箭头函数的参数,可使用rest参数

    var arrow = (a) => {
      console.log(a)          
    }
    arrow('aaa','bbb')          //aaa   虽然有2个参数,但是只能拿到一个
    var restArrow = (...a) => {
      console.log(a)
    }
    restArrow('aaa','bbb')       //[ 'aaa', 'bbb' ]   两个参数以数组形式展现
    

    4. 没有原型对象

    var arrow = ()=>{
      return 1
    }
    var fn = function () {
      return 111
    }
    console.log(fn.prototype,fn.constructor)
    console.log(arrow.prototype,arrow.constructor)
    

    5. this的指向不一样,箭头函数的this指向其上下文的this,任何方法都不可以改变其指向,包括call(), bind(), apply().

    var fn = {
      a:10,
      b:function(){
        console.log('this',this)
        console.log('thisa',this.a)
      },
      c:()=>{
        console.log('this',this)
        console.log('thisa',this.a)
      }
    }
    console.log(fn.b)
    console.log(fn.c)
    fn.b()
    fn.c()
    

    普通函数指向引用对象,箭头函数指向window
    箭头函数不绑定this,会捕获其所在的上下文的this值,作为自己的this值
    var obj = {
      a: 10,
      b: function () {
        console.log(this.a); 
      },
      bb: function () {
        return function () {
          console.log(this.a); 
        }
    
      },
      c:  ()=> {
        console.log(this.a); 
      },
      cc: function () {
        return () => {
          console.log(this.a); 
        }
      }
    }
    obj.b();      //10
    obj.bb()();     //undefined
    obj.cc()();     //10
    obj.c();     //undefined
    

    箭头函数通过 call() 或 apply() 方法调用一个函数时,只传入了一个参数,对 this 并没有影响。

    let obj2 = {
        a: 10,
        b: function(n) {
            let f = (n) => n + this.a;
            return f(n);
        },
        c: function(n) {
            let f = (n) => n + this.a;
            let m = {
                a: 20
            };
            return f.call(m,n);
        }
    };
    console.log(obj2.b(1));  // 11
    console.log(obj2.c(1)); // 11
    

    相关文章

      网友评论

          本文标题:aa.箭头函数

          本文链接:https://www.haomeiwen.com/subject/gmffxktx.html