美文网首页
箭头使用箭头函数,不过以下几种情况避免使用:

箭头使用箭头函数,不过以下几种情况避免使用:

作者: 如果俞天阳会飞 | 来源:发表于2020-11-12 09:45 被阅读0次
  1. 使用箭头函数定义对象的方法
// 例子 3-1

// bad
let foo = {
  value: 1,
  getValue: () => console.log(this.value)
}

foo.getValue();  // undefined
  1. 定义原型方法
// bad
function Foo() {
  this.value = 1
}

Foo.prototype.getValue = () => console.log(this.value)

let foo = new Foo()
foo.getValue();  // undefined
  1. 作为事件的回调函数
// bad
const button = document.getElementById('myButton');
button.addEventListener('click', () => {
    console.log(this === window); // => true
    this.innerHTML = 'Clicked button';
});

例子

  var a = 2;
  const b = 'bbb';
  let foo = {
    a: 1,
    b:'b',
    getValue1: () => {
      console.log(this.a)
    },
    getValue2() {
      console.log(this.a)
    },
    getValue3: () => {
      console.log(this.b)
    },
  };

  foo.getValue1();  // 2
  foo.getValue2();  // 1
  foo.getValue3();  // undefined
  console.log([7].toString()) // 7

相关文章

  • 箭头使用箭头函数,不过以下几种情况避免使用:

    使用箭头函数定义对象的方法 定义原型方法 作为事件的回调函数 例子

  • 使用箭头函数,以下几种情况避免使用

    1.定义对象的方法 2.定义原型上的方法 3.作为事件的回调函数(同上)

  • 5种应该避免使用箭头函数的情况

    摘要: 箭头函数也有可能会有BUG... 原文:几种应该避免使用箭头函数的情况 作者:JS菌 Fundebug经授...

  • 箭头函数(常用)

    ES6 允许使用箭头(=>)定义函数 箭头函数对于使用function关键字创建的函数有以下区别1.箭头函数没有a...

  • 箭头函数

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

  • Es6知识点总结

    methods 不能使用箭头函数 为啥?在箭头函数中使用this的话指向的是组件本身 如果不使用箭头函数 this...

  • 箭头函数

    ES6 允许使用“箭头”(=>)来定义函数。 使用箭头函数,可以在不影响代码可读性的情况下,少写代码。如 用箭头函...

  • ECMAScript 6 箭头函数

    箭头函数 ES6 允许使用“箭头”(=>)定义函数。 使用注意点 箭头函数有几个使用注意点。 (1)函数体内的th...

  • 箭头函数和数组

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

  • React事件绑定

    1、在构造函数内使用bind绑定this 2、箭头函数绑定this 3、使用bind()绑定this 4、使用箭头...

网友评论

      本文标题:箭头使用箭头函数,不过以下几种情况避免使用:

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