Dan
Dan

Reputation: 11114

Variable assignment in jQuery

New to jQuery and having some trouble understanding some of the syntax. What is going on in this code snippet?

var that = $(this),
    url = that.attr('action'),
    method = that.attr('method'),
    data = {};

Is it defining 4 variable or a data structure. This code is inside a jQuery block of code executed when a form is submitted. $(this) is the form being submitted. I'm not even sure where to start Googling.

Upvotes: 1

Views: 364

Answers (1)

David
David

Reputation: 219127

That code is defining 4 separate variables, unrelated to any common data structure. It's equivalent to this:

var that = $(this);
var url = that.attr('action');
var method = that.attr('method');
var data = {};
  • that is defined as a jQuery reference to whatever this is in the context in which this code runs (likely a form element in this case).
  • url is a string, the value of the action attribute on the DOM element.
  • method is a string, the value of the method attribute on the DOM element.
  • data is an empty object.

Note that this is more "JavaScript" syntax than "jQuery" syntax. jQuery is only involved here in how the first three variables get their values. $() is a jQuery function that returns a jQuery object, but the actual syntax of calling it is like any other JavaScript. And .attr() is a function on a jQuery object.

Upvotes: 6

Related Questions