Reputation: 77
If I am making a factory function foo
, why do I not return the inner function as function noiseMade()
rather than just noiseMade()
?
function foo() {
let sound = "buzz"
return {
noiseMade() {
return "I make" + sound
}
}
}
Upvotes: 1
Views: 56
Reputation: 769
To sum up our conversation from the comments. Supported syntax for functions in objects:
{
makeNoise: function() {}
}
// ES6 and above
{
makeNoise() {},
makeAnotherNoise: () => {} // behave a bit different, read about arrow functions for more info
}
If you want to return a function from another function you could i.e.:
const makeNoise = () => {
const sound = 'bork';
return () => { console.log(sound) };
}
Also one additional free comment :) It's preferred to use verbs
for functions names, because functions usually do
stuff :)
Upvotes: 2
Reputation: 314
The syntax you have mentioned:
const obj = {
propertyName() { ... }
};
is a shorthand method declaration introduced in ES6
It is equivalent to a classic declaration:
const obj = {
propertyName: function fnName() { ... }
};
Upvotes: 1