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?
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With