简体   繁体   中英

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?

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM