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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With