美文网首页
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.箭头函数

    1. 是匿名函数,没有名字 2. 不可以用于构造函数,就是new funName() 3. 不具有argument...

  • ES6~箭头函数

    什么是箭头函数 单表达式箭头函数 相当于 多表达式箭头函数 箭头函数相当于匿名函数,并且简化了函数定义。箭头函数有...

  • 箭头函数和立即执行函数

    箭头函数 箭头函数和普通函数有什么区别?如果把箭头函数转换为不用箭头函数的形式,如何转换主要是this的差别,箭头...

  • 学习 ES 6 箭头函数

    箭头函数的用法 ES6 允许使用“箭头”(=>)定义函数。 箭头函数的一个用处是简化回调函数。 箭头函数 this...

  • 箭头函数

    箭头函数 箭头函数能让this的指向固定化 分析:1)第一个setInterval()中使用了箭头函数,箭头函数使...

  • TS  笔记this

    this 箭头函数在箭头函数创建的地方获得this;非箭头函数,在调用函数的地方获得this如图

  • 箭头函数和数组

    箭头函数&数组 箭头函数 特点: 没有 this 没有 arguments 没有prototype在箭头函数中使用...

  • 箭头函数

    箭头函数 为什么使用箭头函数

  • 箭头函数中this的指向

    箭头函数在平时开发中用着非常爽,箭头函数有什么特点呢 箭头函数不能够当做构造函数使用 箭头函数没有argument...

  • js学习笔记4(函数)

    1.箭头函数 ES6新增属性。箭头函数特别适合嵌入函数的场景。 箭头函数虽然语法简介,但是很多场合不适用。箭头函数...

网友评论

      本文标题:aa.箭头函数

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