Arrow functions and regular functions in JavaScript

How is the arrow function different from the regular function in JS?


Since the birth of JavaScript, regular functions have been "old school" functions:

function run() {

}

They can be run directly:

run()

Or you can assign them to variables:

const run = function run() {

}

run()

When doing so, the function canalsoanonymous:

const run = function () {

}

run()

The only difference is that now in the stack trace that appeared when the error occurred, you will no longer see the function name.

The Arrow functions introduced in ES6 in 2015 are a bit like the last version of regular functions because they don't have a name. no way.

The grammatical "footprint" is small:

const run = () => {

}

run()

If there is a parameter, you can omit the parentheses:

const run = param => {

}

run()

If there is only one statement, we can also omit the curly braces:

const run = param => 'running'
run()

In this case, the return value is a string'running'.

Both arrow functions and regular functions can be used as object methods.

Now, the biggest difference between these two functions isthisBind in a method.

Consider the following example:

const car = {
  brand: 'Ford',
  model: 'Fiesta',
  start: function() {
    console.log(`Started ${this.brand} ${this.model}`)
  },
  stop: () => {
    console.log(`Stopped ${this.brand} ${this.model}`)
  }
}

thisinsidestart()The method refers to the object itself.

But whenstop()Method, this is an arrow function, not.

thisNo binding to the object instance. What does it point outthisPoint to the outer range.

this meansArrow function does not apply to object methodsWhen you want to visitthis.

Download mine for freeJavaScript beginner's manual


More js tutorials: