Javascript

I am wondering if there is a way to reduce anonymous function declarations in JavaScript through using a preprocessor / compiler like Google Closure. I suppose that would be pretty neat for callbacks.

For example, usually I write a qunit test case like this:

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

I am looking for some Clojure -inpired syntax:

 test("Dummy test", #(ok ab)); 

Is it possible?

+6
source share
1 answer

Without worrying about preprocessors or compilers, you can do the following, which shortens the callback syntax. One thing is that the scope of "this" is not considered ... but for your use case, I don't think it matters:

 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 your shorthand syntax */ var callback = f(ok,10,10); console.log(callback()); 
+4
source

Source: https://habr.com/ru/post/947182/


All Articles