Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between nameFunction() {} and nameFunction () => {} in ECMA6

I'm start learning Vue.js and ECMA6 syntax, I saw this in the tutorial:

methods: {
  someMethod: function() { 
    console.log(this) // this works
  }
} 

Then I thought the syntax could be:

methods: {
  someMethod: () => {
    console.log(this) // this undefined
  }
}

but this works:

methods: {
  someMethod () {
    console.log(this) // this works
  }
}

Can explain the difference and the ECMA5 syntax?

like image 219
Jepser Bernardino Avatar asked Jul 10 '16 21:07

Jepser Bernardino


People also ask

How are arrow functions () => {} different than traditional function expressions?

Regular functions created using function declarations or expressions are constructible and callable. Since regular functions are constructible, they can be called using the new keyword. However, the arrow functions are only callable and not constructible, i.e arrow functions can never be used as constructor functions.

What does () => mean in JavaScript?

It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.

What's the difference between anonymous function and arrow functions in JavaScript?

An arrow function can be defined in a line, while in the anonymous function we need more than 3 lines for the execution of one statement.

What is the difference between function and method?

A function is a set of instructions or procedures to perform a specific task, and a method is a set of instructions that are associated with an object.


1 Answers

Of your three options, only the first one is supported in ES5. The other two are additions in ES6.

The third option is an ES6 shortcut for the first option and thus they work identically in ES6.

When you use the arrow syntax as in the second one, this is NOT set to be the host object as it is in your first and third. That's one of the features of the arrow syntax and thus it should not be used when you expect this to be set to the host object. Instead, this will be set to the lexical context from where the code was defined - often referred to as "the value of this in the enclosing context" or the "lexical value of this" which in your case would be whatever this was when the host object was initially declared which apparently was undefined.

Here's a good reference article on arrow functions: ES6 In Depth: Arrow functions

like image 52
jfriend00 Avatar answered Oct 21 '22 09:10

jfriend00