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

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

作者: 如果俞天阳会飞 | 来源:发表于2021-02-01 11:41 被阅读0次

1.定义对象的方法

  const obj = {
   name: '张三',
    getName: ()=> {
     console.log(this); // window
    console.log(this.name) // undefined
   }
  };
obj.getName();
// 如果 script type 属性设置 module 还会报错 console.log(this) 是 undefined
<script type="module"></script>

2.定义原型上的方法

  function  Cat(name, age) {
   this.name = name;
   this.age = age;
  }
Cat.prototype.getName = ()=> this.name;
Cat.prototype.getAge = function () {
  return this.age;
};
const cat = new Cat('blue', 10);
console.log(cat.getName()); // ' '
console.log(cat.getAge()); // 10
// 如果 script type属性设置 module (模块)还会报错
<script type="module"></script>

3.作为事件的回调函数(同上)

相关文章

网友评论

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

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