views:

65

answers:

3

Hi, I am having trouble understanding this code:

$.functionone = function(){
  function setOptions(newOptions){
      ...
  }
  this.setOptions = setOptions;
}

what does adding 'this' in 'this.setOptions' for? I understand that its referencing the function setOptions, but does adding the 'this' there make the function get called? I know this refers to the DOM element, but whats the point of having it in this particular scenario. Thanks.

+1  A: 

The code creates a function and adds it as a "setOptions" property of the DOM element.

Presumably, some other part of the code will know to look for a "setOptions" function on the DOM element and execute it.

John Fisher
A: 

this refers to the particular DOM element that called the function.

The following line:

this.setOptions = setOptions;

Means the function "setOptions" is assigned to the "setOptions" property of the DOM Element.

ghoppe
+3  A: 

That will simply expose the function from the scope of functionone, to be a property of the $ object.

For example:

$.functionone = function(){

  function setOptions(newOptions){
    //...
  }
  this.setOptions = setOptions;
};

typeof $.setOptions; // "undefined", it doesn't exist
$.functionone();
typeof $.setOptions; // "function"

The this value on JavaScript is set implicitly when you make a function call.

If the function is bound as a property of an object (like $.functionone), the this value will refer to the base object ($ in your example).

That's not so useful IMO, it's equivalent to:

$.functionone = function(){
  this.setOptions = function (newOptions) {
    //...
  };
};

Which is at the end, when you invoke functionone, equivalent to:

$.setOptions = function (newOptions) {
  //..
};

The difference is that the function is not named, which can be useful for debugging.

Working with the this value on jQuery plugins is more usual when you extend the jQuery.fn object, in that case the this value refers to the jQuery object that contains the matched elements, and not to the jQuery constructor itself.

CMS