According to the documentation in Mozilla
, enviar
despite being the contracted form of enviar: function()
, the contracted form is a named function, while the second is an anonymous function.
Note : The shorthand syntax uses named Function Instead of Anonymous
functions (as in …foo: function() {}…
). Named functions can be called
from the Function body (this is Impossible for Anonymous Function as
there is no Identifier to refer to). For more Details, see Function.
Source: Method Definitions
However if you execute the code below, you will see that the contracted form behaves as an anonymous function, at least it is this behavior that I am having when executing in Opera.
var teste = {
nomeada: function nomeada(imprimir) {
return !imprimir ? nomeada(true) : console.log("nomeada");
},
curta(imprimir) {
return !imprimir ? curta(true) : console.log("curta");
},
anomina: function(imprimir) {
return !imprimir ? anomina(true) : console.log("anomina");
}
}
try {
teste.nomeada();
} catch (e) {
console.error(e.message);
}
try {
teste.curta();
} catch (e) {
console.error(e.message);
}
try {
teste.anomina();
} catch (e) {
console.error(e.message);
}
Another curious point is that in the Mozilla documentation it says that the contracted form cannot be used as.
Method Definitions are not constructable
All method Definitions are not constructors and will throw a Typeerror
if you Try to instantiate them.
Source: Method Definitions
But when executing the code below, I got a different behavior than pointed. At least that’s what happened when running in Opera.
var teste = {
nomeada: function nomeada() {
this.nome = "nomeada";
},
curta() {
this.nome = "curta";
},
anomina: function() {
this.nome = "anomina";
}
}
try {
console.log(new teste.nomeada);
} catch (e) {
console.error(e.message);
}
try {
console.log(new teste.curta);
} catch (e) {
console.error(e.message);
}
try {
console.log(new teste.anomina);
} catch (e) {
console.error(e.message);
}
Another point, as far as browser compatibility is concerned, short functions can only be used in newer/updated browsers. However, since you are using Vuejs, you must be using vue-cli
, the gulp-babel
or whatever solution transposes your Java ES5
for something compatible with old browser, so this is not a problem.
I’m working with
Vue
for over a year, and I never asked myself that question, I always useenviar()
, but if I’m not mistaken, you useenviar: function(){}
has some problems with thethis
.– Rafael Augusto
So, in the documentation I always saw using the form with funcion(){} and then looking at some videos I saw that it was using without, and then with that I arose the doubt.
– Marcelo Diniz
I believe I don’t have much of a difference, which is something like
Arrow Functions
, because if you do a test, and try to use this, it will give an error, Voce will have to uselet self = this
, different if only used with()
– Rafael Augusto