Anonymous function declaration shorthand javascript

白昼怎懂夜的黑 提交于 2019-12-07 01:57:10

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/17079654/anonymous-function-declaration-shorthand-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!