zAnthony
zAnthony

Reputation: 342

What is the difference between vue.js method

I'm currently learning vue.js and see people building their methods differently. I'm curious what is the difference between these two:

One:

greet: function (event) {
   alert('Hello ' + this.name + '!')
}

Two:

greet(event) {
   alert('Hello ' + this.name + '!')
}

Upvotes: 1

Views: 78

Answers (1)

achacttn
achacttn

Reputation: 163

Both versions of the greet function accomplish the same thing.

The first version is more explicit as a key:value pair of an object, where greet is the object's key, with the function being that key's value.

Second version is shorthand (as mentioned in the comments, introduced in ES6).

They are both ways of writing functions as expressions.

Function declarations are similar to writing function expressions, you may be familiar with how they look

function greet(){
    alert('Hello')
}

They start with the function keyword before the name greet. They behave similarly to function expressions.

Where you write expressions in your page of code matters, as they do not load until interpreter reaches the line containing the expression.

Function declarations are hoisted to the top of their context.

More examples and details can be found:

https://developer.mozilla.org/en-US/docs/web/JavaScript/Reference/Operators/function

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function

Upvotes: 2

Related Questions