9

I try to understand how Protovis works, and I stumbled upon code like this:

force.node.add(pv.Dot)
    .size(function(d) (d.linkDegree + 4) * Math.pow(this.scale, -1.5)) // notice this
    .fillStyle(function(d) d.fix ? "brown" : colors(d.group)) // and this
    .strokeStyle(function() this.fillStyle().darker()) // and even this
    .lineWidth(1)
    .title(function(d) d.nodeName)
    .event("mousedown", pv.Behavior.drag())
    .event("drag", force);

I tried rolling my own short functions, like this:

(function(a) a+2)

I am NOT asking about anonymous functions declared like function(){stuff();}. The code in question looks like function() stuff; and it works. I want to know why. I don't want to learn about constructs like myvar = function(a){return a+1;}, but about constructs like myvar = (function(a) a+1). Please look at the above code more carefully.

But, as I suspected, it threw a syntax error.

How can such code work?

(Note: the protovis code does work as intended.)

Gabi Purcaru
  • 30,940
  • 9
  • 79
  • 95
  • 1
    I don't get it. I even checked the grammar specified in the spec - the braces *are* required for anonymous functions: http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf "A.5 Functions and Programs". –  Nov 17 '10 at 16:39

3 Answers3

10

This is a Expression Closure that was introduced in JavaScript 1.8. It is an extension to ECMAScript.

https://developer.mozilla.org/en/JavaScript/New_in_JavaScript/1.8

ChaosPandion
  • 77,506
  • 18
  • 119
  • 157
  • 3
    Finally. an answer that understood the question! – SLaks Nov 17 '10 at 16:42
  • @lincolnk - For compatibilities sake that is true but something like this should really be built into ECMAScript. – ChaosPandion Nov 17 '10 at 16:51
  • 2
    why? trading explicitness for shorter code seems like a bad trade. – lincolnk Nov 17 '10 at 16:52
  • @lincolnk - I am of the camp that feels that core language features should be as short as possible but no shorter. Have you ever seen a considerably sized project that didn't use lambdas all over the place? The expression closure syntax is still a bit heavy because of the `function` keyword but the majority of the noise is removed. The same idea is used in C# with lambda expressions. – ChaosPandion Nov 17 '10 at 16:55
  • 1
    I'm all for short lambdas. But this still sounds like a bad idea, especially since they didn't shorten the `function`, which is about as long the braces and the `return`. Real solution: use Coffeescript :) –  Nov 17 '10 at 17:10
2

Protovis also has its own code to handle the case where the browser you're running does not yet support the Expression Closure format, here: http://vis.stanford.edu/protovis/jsdoc/symbols/src/src_pv-internals.js.html

Hellion
  • 1,740
  • 28
  • 36
  • Thanks! I was stumped trying to determine what ` – RobM Jan 06 '11 at 14:52
1

This is an Expression Closure, see this:

Here's the jsfiddle that works:

icyrock.com
  • 27,952
  • 4
  • 66
  • 85