About the advantages and disadvantages of arrow functions in ES6 and scenarios where they cannot be used

About arrow functions

Everyone is familiar with the arrow function. Its biggest function is to change the direction of this.

Advantages of arrow functions

1-Abbreviated function

function fn = ()=>{}

2-Change the pointing of this, the this of the arrow function points to the current object

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();

Disadvantages of arrow functions

1-No arguments parameters

2- The point of this cannot be changed through apply bind call

What scenarios cannot arrow functions be used for?

1- Cannot be used for object methods

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

2- Cannot be used for object prototypes

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

3- Cannot be used in constructors

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- Dynamic context

错误写法
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 life cycle and methods

In vue, you should write according to the syntax of vue and do not use arrow functions. For example

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

//错误

created:()=>{}

//正确

created(){}

Guess you like

Origin blog.csdn.net/wuguidian1114/article/details/123338963