1

Ahoi community,

Is there a possibility to define an alias for the javascript keyword "Function"?

var f = Function; // define Function alias

var foobar = f() // write 'f' as replacement for 'function'
{        
    console.log("foobar") 
};

foobar();
  • 1
    You can't create aliases for keywords, though [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) is not a keyword, it's the name of a function. – Teemu Mar 10 '16 at 18:28
  • 1
    It's definitely not, but why do you need this? – u_mulder Mar 10 '16 at 18:28
  • Its just like asking, I want to create an alias for `var`. `function` is a javascript reserved keyword. – Rajaprabhu Aravindasamy Mar 10 '16 at 18:29
  • @RajaprabhuAravindasamy `function` != `Function` – Dave Newton Mar 10 '16 at 18:30
  • @DaveNewton `Function` can be saved as a reference somewhere. But by looking at OP's approach, I suspect his aim was just creating an alias for `function` keyword. :) – Rajaprabhu Aravindasamy Mar 10 '16 at 18:32
  • `constructor.constructor("return 123*456")()` surprises many devs... – dandavis Mar 10 '16 at 18:33
  • 1
    There are [arrow functions](https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions/Arrow_functions). – Sebastian Simon Mar 10 '16 at 18:37
  • Thanks Xufox. Arrow functions are close to what I was looking for. – tassfighter Mar 13 '16 at 16:23
  • As for why this would be useful, it would allow greater compression by JS minifiers, as well as more readable code with lots of closures or anonymous functions. Like `var a = b(fn(){});` versus `var a = b(function(){});`. Most JS libraries use aliases, like the common `$ = function(id){return document.getElementById(id);}`. – Beejor Oct 17 '16 at 05:14

3 Answers3

1

No you cannot, but you can have anonymous functions, named functions and/or function expressions.

For example,

//named function
function Test( param1, param2) { /* code goes here */}

//function expression
var foo = function (param1, param2) { /* code goes here */}
foo('test1','test2')

//anonymous function
function (param1, param2) { /* this is one is problematic */}

I recommend you go through a javascript tutorial basics.

mugabits
  • 1,015
  • 1
  • 12
  • 22
1

Arrow functions is what I was looking for (thx Xufox).

It's useful to minify your JS (thx Beejor).

To me it is also better readable and faster to code :)

So the snippet in the original question would look like:

var foobar = () => console.log("foobar"); 

foobar();
0

If your question is more similar to this

How can I simulate macros in JavaScript?

Then take a look at http://sweetjs.org/ doc.

Community
  • 1
  • 1
Gaurav Ingalkar
  • 1,217
  • 11
  • 20