New to javascript here.
So I've been trying to learn to use Raphael.js and came across this http://jsfiddle.net/terryyounghk/AeU2r/ snippet of code.
Now if you look at line 167, there is this "if" statement I just don't understand.
Raphael.el.style = function (state, style, aniOptions)
{
if (!this.class)
{
this.class = style ? style : 'default';
this.aniOptions = aniOptions ? aniOptions : null;
// start assigning some basic behaviors
this.mouseover(function () { this.style('hover'); });
....
What class? What is it returning? Who is returning it?
What is it even checking? That it's a class?
From the Raphael documentation, Raphael.el is a way of adding one's own methods to the Raphael.element class. In general, the purpose of this class is to make it easier to manipulate SVG elements.
this.class in the code example has nothing to do with the the word class in the programming sense, as used in the preceding sentences. Nor (as far as I can see) is it part of the standard Raphael framework. Nor does it refer to the class attribute that HTML and SVG elements can have, and which is usually accessed in javascript using element.className or element.setAttribute('class', '...').
this refers to the element wrapper object (an instance of Raphael.element), and it seems that the person who wrote this method has simply used the name class to store some additional information in the element wrapper. (As pointed out in comments, this might be a bad idea because class is a reserved keyword in javascript; but anyway, it works.)
Specifically, in the example, this.class is initially undefined because it has not been assigned a value anywhere else in Raphael or in the code. In the if clause, !undefined evaluates to true, and in the following line, no value has been passed to the function for style, so that style ? style : 'default' evaluates to 'default'. So this.class is assigned the value 'default'. Afterwards, if you right-click on a shape and choose Use custom style, the class for that shape becomes 'custom'.
Note that javascript very easily lets you refer to, and assign values to, properties of an object that have not been initialised anywhere. It does not throw an error but simply returns undefined if no value has been assigned.
You can see all this by inserting a line that logs what's going on to the browser console:
console.log('style', state, style, aniOptions, this, 'class:', this.class);
and then using your browser's developer tools to see the output (JSFiddle).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With