Reputation: 6856
This my code
const x = {
a() {
console.log("a");
},
b: function() {
console.log("b");
},
};
Is there a difference between a
& b
functions?
I read somewhere, that the a() {}
way of creating methods is shorter, but can bring a number of problems.
Use it only in those cases when you are sure that you will never use recursion or pass a function to events handlers.
Is this true?
Upvotes: 2
Views: 250
Reputation: 370729
The only real difference is that a
is defined as a method, meaning that it can't be instantiated with new
:
const x = {
a() {
},
b: function() {
}
};
new x.b();
new x.a();
A trivial difference is that, in sloppy mode, the method has the arguments
and caller
properties on its internal prototype, whereas the function has those properties on the function object itself:
const x = {
a() {
},
b: function() {
}
};
console.log(x.a.hasOwnProperty('arguments'), x.a.hasOwnProperty('caller'));
console.log(x.b.hasOwnProperty('arguments'), x.b.hasOwnProperty('caller'));
Accessing these properties is forbidden in strict mode, and in method definitions. They are deprecated.
Upvotes: 4