I think you're saying that you want myFunction
to return a function that returns the alphabet, but which also has a
and b
functions on it.
You can do that, since functions are objects, and objects can have arbitrary properties. There's no literal syntax for functions plus properties, but you can easily add them via assignment or with Object.assign
:
let myFunction = (data) => Object.assign(
() => "abcdefghijklmnopqrstuvwxyz",
{a, b}
);
let a = () => {
return "a";
};
let b = () => {
return "b";
};
console.log(myFunction().a());
//=> "a"
console.log(myFunction()());
// ^^−−−−−−−−−−− Note the extra ()
//=> "abcdefghijklmnopqrstuvwxyz"
For clarity, here's a more verbose version of myFunction
:
let myFunction = (data) => {
const alphabet = () => "abcdefghijklmnopqrstuvwxyz";
alphabet.a = a;
alphabet.b = b;
return alphabet;
);
The original above does the same thing (other than that this more verbose version gives alphabet
a name), but this version may be easier to read.
Or you can have the name like this, too:
let myFunction = (data) => {
const alphabet = () => "abcdefghijklmnopqrstuvwxyz";
return Object.assign(alphabet, {a, b});
);
In a comment you've said:
I would like to call myFunction() without the extra ()'s and get the full alphabet
That's basically not possible. You can get close, but you can't literally get there.
The "close" you can get to is that you can return a String
object rather than a string primitive:
let myFunction = (data) => Object.assign(
new String("abcdefghijklmnopqrstuvwxyz"),
{a, b}
);
let a = () => {
return "a";
};
let b = () => {
return "b";
};
console.log(myFunction().a());
//=> "a"
console.log(myFunction());
//=> "abcdefghijklmnopqrstuvwxyz"
String
objects are objects, not just string primitives, which means they can have additional properties, like a
and b
. But any time they're coerced to a primitive form, they go back to being a string primitive. For instance, if you use +
on them. Also, String
objects have all the String
methods (they get them from the same place string primitives do), and the ones that return strings return string primitives, so calling (for instance) toLowerCase
on the result also gives you a string primitive. Here's an example of both +
and toLowerCase()
:
let myFunction = (data) => Object.assign(
new String("abcdefghijklmnopqrstuvwxyz"),
{a, b}
);
let a = () => {
return "a";
};
let b = () => {
return "b";
};
console.log(myFunction().a());
//=> "a"
console.log("alphabet: " + myFunction());
//=> "abcdefghijklmnopqrstuvwxyz"
console.log(myFunction().toLowerCase());
//=> "abcdefghijklmnopqrstuvwxyz"
I do not recommend doing this. Again, String
objects are objects, not the usual kind of strings, and that will likely cause some trouble in your program at some point.