jjei
jjei

Reputation: 1290

Where 'this' refers to in this sample of jquery code?

Here http://www.quirksmode.org/js/this.html it says that "In JavaScript this always refers to the “owner” of the function we're executing, or rather, to the object that a function is a method of."

However, I'm confused where this refers in the code sample below because of the nested anonymous functions.

Drupal.behaviors.ajaxPoll = function(context) {
  $('form.ajax-poll:not(.ajax-poll-processed)', context).addClass('ajax-poll-processed').each(function() {
    // Find the form and poll wrapper items that will be affected.
    var $form = $(this);
    var $pollWrapper = $form.parents('.poll_content, .poll').filter(':first');

...

Is the object of the function (which is referring to this) Drupal.behaviors.ajaxPoll?

Also, I have understood that writing $form is basically the same as writing jQueryform. What is the logic of using a $ -sign in the name of a variable?

Upvotes: 0

Views: 85

Answers (3)

John Smith
John Smith

Reputation: 2332

In this case this referes to each form element, that the selector matched.

But from a technical perspective it entirely depends on how the each method is implemented.

jquery's each is implemented using javascripts apply method which allows to define manually what this refers to inside a method (which is as I said each form element).

Upvotes: 1

Simon Rapilly
Simon Rapilly

Reputation: 393

Can't answer for sure on the first question, but I can for the second one:

It's just a naming convention to designate JQuery objects nothing special about that, see the answer here, behind it's a Javascript object

Upvotes: 0

jods
jods

Reputation: 4591

In javascript, this is dynamic. Depending on where/how a function is called, it can take different values. This is much unlike most OO language you may know, where you can statically define the value of this.

In your example, jQuery documentation for each states that this will be set to the element currently enumerating. So it should be an HTML form element.

This (no pun intended) is one very confusing aspect of javascript, there is a lot written about it on the internet, which I encourage you to read.

Note that you can fix the value of this inside a function to a specific value, no matter the caller, using bind.

Upvotes: 1

Related Questions