Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird Javascript expression

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.)

like image 249
Gabi Purcaru Avatar asked Nov 17 '10 16:11

Gabi Purcaru


3 Answers

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

like image 53
ChaosPandion Avatar answered Oct 15 '22 04:10

ChaosPandion


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

like image 23
Hellion Avatar answered Oct 15 '22 04:10

Hellion


This is an Expression Closure, see this:

  • http://asserttrue.blogspot.com/2009/07/javascript-expression-closures-and-why.html

Here's the jsfiddle that works:

  • http://jsfiddle.net/fyB9h/
like image 20
icyrock.com Avatar answered Oct 15 '22 04:10

icyrock.com