views:

118

answers:

6

I saw a fn use in raphael, which is a javascript lab.

Raphael.fn.g.piechart = function (cx, cy, r, values, opts) {
  // blah...blah
}

it extend raphael, so people can uses like r = Raphael; r.g.piechart.

I search google and have nothing seem to be clear my mind. hope you help.

A: 

Its short for function

Petah
+3  A: 

Initially it's just an empty object created along with Raphael, it's literally just:

Raphael.fn = {};

It's a common place for plugins to be stored, and they're called from there when a new instance is created.

Nick Craver
Yup, line 109 of [ **the uncompressed version** ](http://github.com/DmitryBaranovskiy/raphael/raw/master/raphael.js) ==> `R.fn = {};`, and the last line is essentially `Raphael = R`. It look like line 1801 in the function `create()` (which is used to help make the Raphael instance on line 19 ==> `return create[apply](R, arguments);` ) checks for plugins `plugins.call(container, container, R.fn);`
Peter Ajtai
+1  A: 

fn is nothing special in JavaScript. It's just the name of a property Raphael uses. See http://raphaeljs.com/reference.html

RoToRa
+1  A: 

Nothing special with fn in JavaScript.

Q_the_dreadlocked_ninja
+2  A: 

In your own JS code It can be whatever you want - it's not a reserved word, it doesn't have any special meaning, so you can name variable or method fn just like you can use names like foo or myVariable. In jQuery, for example, jQuery.fn === jQuery.prototype (a shortcut for plugin authors).

pawel
+1  A: 

fn is used for adding your own methods to the canvas.

Any methods you add to fn will work on the canvas. This is in contrast to methods that would work on for example an element ( for which you would use el).

Since extending the fn object will act on the canvas, you must add your custom methods before creating your Raphael instance (this is not true if you are extending the el of an element).

For example, from the documentation:

  // Extend Raphael fn object by adding methods to it:
Raphael.fn.arrow = function (x1, y1, x2, y2, size) {
    return this.path( ... );
}; 
  // or add namespaces to it:
Raphael.fn.mystuff = {
    arrow: function () {…},
    star: function () {…},
    // etc…
};

  // Now when you create a Raphael instance, your custom
  // methods are available.
var paper = Raphael(10, 10, 630, 480);

  // Using custom methods:
paper.arrow(10, 10, 30, 30, 5).attr({fill: "#f00"});

  // Using name spaced custom methods
paper.mystuff.arrow();
paper.mystuff.star();
Peter Ajtai