anthonypliu
anthonypliu

Reputation: 12437

How does using 'this' in a simple jquery function work?

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.

Upvotes: 2

Views: 124

Answers (3)

Christian C. Salvadó
Christian C. Salvadó

Reputation: 827198

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.

Upvotes: 3

ghoppe
ghoppe

Reputation: 21784

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.

Upvotes: 0

John Fisher
John Fisher

Reputation: 22721

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.

Upvotes: 1

Related Questions