关于ES6中的箭头函数的优缺点和不能使用的场景

关于箭头函数

箭头函数这个大家都不陌生,他最大的功能就是在于能改变this的指向

箭头函数的优点

1-简写了函数

function fn = ()=>{}

2-改变了this的指向,箭头函数的this指向当前的对象

let obj = {
  a: "a",
  getA: function () {
    setTimeout(function () {
      console.log(this.a); //undefined 因为此时 this 指向 window
    });
  },
};

let obj1 = {
  a: "A",
  getA: function () {
    setTimeout(() => {
      console.log(this.a);//A this指向obj1
    });
  },
};
obj.getA();
obj1.getA();

箭头函数的缺点

1-没有arguments 参数

2- 无法通过 apply bind call 来改变 this的指向

箭头函数不能用于哪些场景

1- 不能用于对象方法

const obj = {
    a:'a'
    getA: () => {
        return this.a
    }
}
console.log( obj.getA() ) //undefined

2- 不能用于对象原型

const obj = {
  name: "name",
};
obj.__proto__.getName = () => {
  console.log(this);// {}
  return this.name;
};
console.log(obj.getName());//undefined

3- 不能用于构造函数

const Person = (name, age) => {
  this.name = name;
  this.age = age;
};
const p1 = new Person("章三", 18); //报错  Person is not a constructor


正确写法:
const Person = function (name, age) {
  this.name = name;
  this.age = age;
};
const p1 = new Person("章三", 18); 
console.log(p1); //Person { name: '章三', age: 18 }

4- 动态上下文

错误写法
const div = document.getElementById('#div')
div.addEventListener('click', () => {  
    this.innerHTML = 'div'
})

正确写法
const div = document.getElementById('#div')
div.addEventListener('click', function() {  
    this.innerHTML = 'div'
})

5- Vue 生命周期和方法

在vue中要按照vue的语法写,不要使用箭头函数例如

 methods: {
          //错误
        functionA: () => {
            return this.data
        },
    //正确
       functionA(){
            return this.data
        },
    }

//错误

created:()=>{}

//正确

created(){}

猜你喜欢

转载自blog.csdn.net/wuguidian1114/article/details/123338963