markdown ES6箭头功能

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown ES6箭头功能相关的知识,希望对你有一定的参考价值。

### An Empty function (no body)
```sh
const func1 = () => { };
```

### Single Parameter
```sh
const add1 = x => x + 1;
```

### Multiple parameters
```sh
const sum = (num1, num2) => num1 + num2;

const sum = (num1, num2) => {
    return num1 + num2;
}
```

### Returning Objects
```sh
const details = name => ({ firstName: name }); // Nice
const details = name => { firstName: name }; // Undefined without the ( )
```

### As Callbacks
```sh
const powerOf2 = [1, 2, 3, 4].map(el => el ** 2) 
// [ 1, 4, 9, 16 ]
```





An Arrow Function does not define local bindings for arguments, super, this, or new.target. Any reference to arguments, super, this, or new.target within an ArrowFunction must resolve to a binding in a lexically enclosing environment.

- Can’t use arguments special variable.
- Can’t be used as a constructor.
There is no internal method [[Construct]] which allows a normal function to be called by new and no prototype property. Also, Arrow functions do not have their own new.target property, and hence, cannot be used as constructor functions. Rewriting the Person function using arrow functions 
```sh
const Person = name =>  {
  this.name = name;
}
const person1 = new Person('Arfat'); // Will throw an error
```

- Can’t change the this binding.
- Can’t be used as generator functions

It is important to note that arrow functions are anonymous, which means that they are not named.

This anonymity creates some issues:
1. Harder to debug

When you get an error, you will not be able to trace the name of the function or the exact line number where it occurred.

2. No self-referencing

If your function needs to have a self-reference at any point (e.g. recursion, event handler that needs to unbind), it will not work.
## Main benefit: No binding of ‘this’

In classic function expressions, the this keyword is bound to different values based on the context in which it is called. With arrow functions however, this is lexically bound. It means that it usesthis from the code that contains the arrow function.

For example, look at the setTimeout function below:

```sh
// ES5
var obj = {
  id: 42,
  counter: function counter() {
    setTimeout(function() {
      console.log(this.id);
    }.bind(this), 1000);
  }
};
```

In the ES5 example, .bind(this) is required to help pass the this context into the function. Otherwise, by default this would be undefined.

```sh
// ES6
var obj = {
  id: 42,
  counter: function counter() {
    setTimeout(() => {
      console.log(this.id);
    }, 1000);
  }
};
```

ES6 arrow functions can’t be bound to a this keyword, so it will lexically go up a scope, and use the value of this in the scope in which it was defined.
## When you should not use Arrow Functions
After learning a little more about arrow functions, I hope you understand that they do not replace regular functions.

Here are some instances where you probably wouldn’t want to use them:

1. Object methods

When you call cat.jumps, the number of lives does not decrease. It is because this is not bound to anything, and will inherit the value of this from its parent scope

```sh
var cat = {
  lives: 9,
  jumps: () => {
    this.lives--;
  }
}
```

2. Callback functions with dynamic context

If you need your context to be dynamic, arrow functions are not the right choice. Take a look at this event handler below:
```sh
var button = document.getElementById('press');

button.addEventListener('click', () => {
  this.classList.toggle('on');
});
```

If we click the button, we would get a TypeError. It is because this is not bound to the button, but instead bound to its parent scope.

3. When it makes your code less readable

It is worth taking into consideration the variety of syntax we covered earlier. With regular functions, people know what to expect. With arrow functions, it may be hard to decipher what you are looking at straightaway.


## When you should use them

Arrow functions shine best with anything that requires this to be bound to the context, and not the function itself.

Despite the fact that they are anonymous, I also like using them with methods such as map and reduce, because I think it makes my code more readable. To me, the pros outweigh the cons.

Thanks for reading my article, and clap if you liked it! Check out my other articles like How I built my Pomodoro Clock app, and the lessons I learned along the way, and Let’s demystify JavaScript’s ‘new’ keyword.

以上是关于markdown ES6箭头功能的主要内容,如果未能解决你的问题,请参考以下文章

javascript ES6箭头功能简短

javascript 箭头功能(ES2015)ES6

为啥我不能在 JavaScript/ES6 中使用带有箭头函数的`new`? [复制]

markdown ES6咖喱功能

jQuery 和 ES6 箭头函数 [重复]

ES6新特性2:箭头函数