匿名函数声明简写javascript [英] Anonymous function declaration shorthand javascript

查看:329
本文介绍了匿名函数声明简写javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有任何方法通过使用预处理器/编译器如Google Closure缩短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.

例如,通常我会这样写一个qunit测试用例:

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

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

我正在寻找一些Clojure风格的语法如下:

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

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

是否有可能?

推荐答案

不用担心预处理器或编译器,您可以执行以下操作,缩短回调语法。有一件事是,这个的范围不处理...但对于你的用例我不认为这很重要:

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

这篇关于匿名函数声明简写javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆