Hello, nice to meet you.
I'm studying the arrow function of ES6.
There was a code example below, saying, "The arrow function can also be used as an immediate execution function."
const person = ( name => ({
sayHi() { return `Hi? My name is ${name}.`; }
}))('Lee');
console.log(person.sayHi()); // Hi? My name is Lee.
In the code above, I know that the bracket to the left of the name parameter is the bracket that starts the execution function immediately, but to the right of the arrow, why is the body of the function wrapped in bracket again?
After searching, if the arrow function returns an object literal, the object literal must be wrapped in brackets (). That's what they say.
The arrow function returns a function called sayHi(), but in JavaScript, is it because the function is also an object?
Does sayHi() mean object literal in this case?
Thank you for reading!
javascript es6
If you solve the code you used as an example, it looks like this.
const person = (function(name) {
return {
sayHi: function() {
return `Hi? My name is ${name}`;
}
};
})('Lee');
In other words, the return value of the immediate execution function is an object with the sayHi function as a property, not the sayHi function.
To return a function, it has to be as below.
const sayHi = (name => () => `Hi? My name is ${name}`)('Lee');
console.log(sayHi());
For reference, the function that returns the function is called a high-order function and is a commonly used pattern.
© 2024 OneMinuteCode. All rights reserved.