1

I've been reading a bit of D3s source code and found this interesting pattern in pie.js. After being defined as an "inner function" it has new "methods" added to it before being returned as some kind of hybrid function / object bastard. Can someone explain what is going on here?

https://github.com/mbostock/d3/blob/876e764429bb4c1201b055d8cf7d5d353ed6226c/src/layout/pie.js#L12

Kimble
  • 7,295
  • 4
  • 54
  • 77
  • Look at this -- http://stackoverflow.com/questions/5647258/how-to-use-revealing-module-pattern-in-javascript – Jeremy J Starcher Apr 20 '14 at 17:29
  • I created a jsfiddle to illustrate the part that puzzled me. I had no idea that it was possible to create this function / object hybrid. http://jsfiddle.net/A7Xv7/ – Kimble Apr 20 '14 at 17:41

1 Answers1

1

that is called a closure. it encapsulates what is inside/creates a new instance and mostly (depending on how used) can only be run once. It is also used to capture variables in loops.

The way it is used within D3 is to let it load when it needs to be loaded. Aka Lazy Loading.

japrescott
  • 4,736
  • 3
  • 25
  • 37
  • The thing that puzzled me was that they in line 12 define pie as a function, then later on (line 54, 66, ..) they add fields to it like it was an object. – Kimble Apr 20 '14 at 17:37
  • 1
    well, try to remain calm while I explain :) in JavaScript, there is no "map". Its called an Object (key->value). And an Object is the base of everything (everything 'inherits' from Object). Thus, a function is actually also an object and as such, can be treated as one. Regarding "inheritence", javascript doens't do polymorphism, but does something called prototype chaining (google it, there are tons of superb tutorials explaining the difference in detail) – japrescott Apr 20 '14 at 17:42
  • Thanks, I realized my map mistake and corrected my comment just before you wrote me back. What you say about a function actually being an object in javascript cleared things up for me. Thanks :-) – Kimble Apr 20 '14 at 17:46