r/javascript • u/erikwendel • Dec 13 '18
The 7 ways of creating a function
https://javascript.christmas/2018/1311
u/senocular Dec 13 '18
This post appears absolute in what its covering: THE 7 ways... when there are a number of kinds of functions not covered. It also gets a little hard to quantify when considering the kinds of modifiers available for many of them (async etc).
I'll try to see what I can come up with for variations:
// function declaration
[async] function [*] <name> () {}
// function expression
// (in expression context)
[async] function [*] [name] () {}
// arrow function
// (generator [*] stage 1)
[async] () => [*] {}
// object initializer shorthand
{
[async] [get] [set] [*] <name> () {}
}
// function constructor
Function()
new Function()
GeneratorFunction()
new GeneratorFunction()
AsyncFunction()
new AsyncFunction()
// class syntax
// (decorator stage 2)
[@decorator] class [name] [extends <expression>] {
[constructor () {}]
}
// class method
// (decorator stage 2)
// (private [#] stage 3)
class {
[@decorator] [static] [async] [get] [set] [*] [#]<name> () {}
}Note: not all the combinations of identifiers work together, for example get and set would not be used for the same definition.
Turns out I came up with 7 too :D, just a different kind of 7 from the OP.
Worthy mentions:
bind()creates a new function from an existing function with unique behaviors for contexteval()can create functions from strings, though through strings using the previously mentioned syntaxes
3
u/lhorie Dec 13 '18
Small nit: the bindings
GeneratorFunctionandAsyncFunctiondon't actually exist in the global scope. You can only get a reference to them by grabbing the constructor of the prototype of said functions.There are also a few more obscure ways to create functions through various APIs:
via
WebAssembly.instantiatevia
new Proxy(target, {apply() {}})via
Object.create(fn)
1
u/erikwendel Dec 13 '18
Todays post in the daily javascript advent calendar at javascript.christmas!
2
Dec 13 '18
Sorry, you have to wait a bit longer
We're happy to see you're so eager - but you have to waitabout 6 hours.
2
u/Delioth Dec 13 '18
I don't know if it's viable to call creation of a generator a different way to create a function. Since it doesn't really create a function, it creates a generator - similar to a function, but not the same thing.
3
u/dwighthouse Dec 13 '18
Seems to be blocked for another 5 hours.