Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous function declaration shorthand javascript

I'm wondering whether there is any way to shorten anonymous function declaration in JavaScript through the utilization of preprocessor/compiler like Google Closure. I figure it'd be quite neat for callbacks.

For example, normally I'd write a qunit test case this way:

test("Dummy test", function(){ ok( a == b );});

I'm looking for some Clojure-inspired syntax as followed:

test("Dummy test", #(ok a b));

Is it possible?

like image 272
Lim H. Avatar asked Jun 13 '13 05:06

Lim H.


1 Answers

Without worrying about preprocessors or compilers, you could do the following which shortens the callback syntax. One thing with this is that the scope of "this" isn't dealt with...but for your use case I don't think that's important:

var ok = function(a,b) {
  return (a==b);
};

var f = function(func) {
  var args = Array.prototype.slice.call(arguments, 1);

  return function() {
    return func.apply(undefined,args);
  };
};

/*
Here's your shorthand syntax
*/
var callback = f(ok,10,10);

console.log(callback());
like image 189
will.ogden Avatar answered Oct 19 '22 12:10

will.ogden