Search code examples
jqueryobjectparallax

understanding a function in a Jquery plugin


There is this following snippet of code from a parallax Jquery pluggin :

function Plugin( element, options ) {
    this.element = element;
    this.$element = $(this.element);

    this.options = $.extend( {}, defaults, options) ;

    this._defaults = defaults;
    this._name = pluginName;

    this.init();
}

The plugin can be found on github : git link

now there are 2 really confusing line :

    this.element = element;
    this.$element = $(this.element);

what i understand is : the value passed to the function Plugin is stored in this.element in the 1st line , now why on the 2nd line is the author adding another variable this.$element and passing the value of $(this.element) to it . ? what's the purpose ?

on asking one of my senior colleagues i got the following answer : this.element = element is setting the element property of whatever object "this" refers to. It is setting it to the value that is held by the variable element.

this.$element = $(this.element) is setting the value of the $element property of the same object. In this case it is setting it to the jQuery object.

But still i don't get what the 2 lines of code are doing .

Also , could't those lines of code I.E. :

this.element = element;
this.$element = $(this.element);

be re-written as :

this.$element = element; ?? 

i tried doing that , and the plugin would't work .

Thank you.

Tenali .


Solution

  • function Plugin( element, options ) is most likely a javascript constructor and will be used like that:

    var plugin = new Plugin(myDiv, options);
    

    this will then be a reference to the new object created. (the plugin object in my example)

    In this context: element would be a reference to any DOM element passed to the Plugin constructor and $(element) would be the jQuery selector for this dom element, on which jQuery functions may be called.