美文网首页
箭头函数

箭头函数

作者: 春饼sama | 来源:发表于2019-02-18 12:09 被阅读0次

箭头函数

箭头函数能让this的指向固定化

function Timer() {
  this.s1 = 0;
  this.s2 = 0;
  // 箭头函数
  setInterval(() => this.s1++, 1000);
  // 普通函数
  setInterval(function () {
    this.s2++;
  }, 1000);
}

var timer = new Timer();

setTimeout(() => console.log('s1: ', timer.s1), 3100);
setTimeout(() => console.log('s2: ', timer.s2), 3100);
// s1: 3
// s2: 0

分析:
1)第一个setInterval()中使用了箭头函数,箭头函数使this绑定定义时所在的作用域,this指向固定
2)第二个setInterval()中使用了普通函数,只想运行时的作用域 即全局对象

箭头函数转成 ES5 的代码

// ES6
function foo() {
  setTimeout(() => {
    console.log('id:', this.id);
  }, 100);
}

// ES5
function foo() {
  var _this = this;

  setTimeout(function () {
    console.log('id:', _this.id);
  }, 100);
}

箭头函数中不存在this 引用外部this
除了this,以下三个变量在箭头函数之中也是不存在的,指向外层函数的对应变量:arguments、super、new.target

箭头函数的不适合场景

const cat = {
  lives:9,
  jumps:()=>{
    this.lives--
  }
}

箭头函数中的this指向了window,静态化了
普通函数 this指向cat

需要动态this 难怪addEventListenr中不能使用箭头函数

// 这里this指向了window  会报错
let button = document.getElementById('press');
button.addEventListener('click', () => {
  this.classList.toggle('on');
});

修改为:
button.addEventListener('click', function(e) {
  this.classList.toggle('on');
});

结论:回调函数里面使用了this的不要使用箭头函数

相关文章

  • ES6~箭头函数

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

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

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

  • 学习 ES 6 箭头函数

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

  • 箭头函数

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

  • TS  笔记this

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

  • 箭头函数和数组

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

  • 箭头函数

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

  • 箭头函数中this的指向

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

  • js学习笔记4(函数)

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

  • js理解普通函数和箭头函数

    普通函数: 箭头函数: 区别: 构造函数和原型 箭头函数不能作为构造函数 不能new。会报错 箭头函数没有原型属性...

网友评论

      本文标题:箭头函数

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