54

In jquery, what does this means and when it is used?

JCm
  • 1,709
  • 6
  • 23
  • 38
  • 1
    the current element... example this textbox will contain abcde when you click on it... – Oliver M Grech Nov 16 '10 at 15:52
  • 14
    the concept of 'this' is JavaScript is, imho, one of the most complicated subjects of the language. I would highly recommend reading up on it if you intend on doing much JavaScript. And, when you think you understand, go back and read about it again, because if you're like me you didn't actually understand the first time you thought you understood. – Matt Nov 16 '10 at 15:55
  • Related: http://stackoverflow.com/questions/133973/how-does-this-keyword-work-within-a-javascript-object-literal – Ciro Santilli新疆棉花TRUMP BAN BAD May 26 '14 at 21:12
  • @Matt ya, you are right:) We all are over-confident people. – Bimal Das Feb 24 '17 at 10:41
  • concept of this is explained here https://scotch.io/@alZami/understanding-this-in-javascript – AL-zami Sep 11 '17 at 05:20

6 Answers6

95

this in JavaScript is very special and powerful. It can mean just about anything. I cover some of it here and here, but it's really worth finding a good tutorial on JavaScript and spending some time with it.

Let's look at jQuery's use of it first, then talk about it more generally in JavaScript (a bit).

In jQuery, specifically

In code written with jQuery, this usually refers to the DOM element that's the subject of the function being called (for instance, in an event callback).

Example jQuery event callback (what this is is covered in the .bind docs):

$("div").click(function() {
    // Here, `this` will be the DOM element for the div that was clicked,
    // so you could (for instance) set its foreground color:
    this.style.color = "red";

    // You'll frequently see $(this) used to wrap a jQuery object around the
    // element, because jQuery makes lots of things a lot simpler. You might
    // hide the element, for example:
    $(this).hide();
});

Similarly, various jQuery functions that act on all of the elements matched by the current jQuery selector can optionally accept a function, and when that function gets called, this is again the DOM element in question — for instance, the html function allows this:

// Find all divs inside the `foo` element, and set
// their content to their CSS class name(s)
// (Okay, so it's a hokey example)
$("#foo div").html(function() {
    return this.className;
});

Another place jQuery uses this is in the callback on jQuery.each:

var a = ["one", "two", "three"];
jQuery.each(a, function() {
    alert(this);
});

...which will alert "one", then "two", then "three". As you can see, this is a totally different usage of this.

(Confusingly, jQuery has two functions called each, the one above which is on the jQuery/$ function itself and always called that way [jQuery.each(...) or $.each(...)], and a different one on jQuery instances [objects] rather than the jQuery/$ function iself. Here are the docs for the other one, I don't discuss the other one in this answer because it uses this the same way html and event callback do, and I wanted to show a different use of this by jQuery.)

Generically in JavaScript

this refers to an object. Update: As of ES5's strict mode, that's no longer true, this can have any value. The value of this within any given function call is determined by how the function is called (not where the function is defined, as in languages like C# or Java). The most common way to set up this when calling a function is by calling the function via a property on the object:

var obj = {};
obj.foo = function() {
    alert(this.firstName);
};
obj.firstName = "Fred";
obj.foo(); // alerts "Fred"

There, because we called foo via a property on obj, this was set to obj for the duration of the call. But don't get the impression that foo is in any way married to obj, this works just fine:

var obj = {};
obj.foo = function() {
    alert(this.firstName);
};
obj.firstName = "Fred";
obj.foo(); // alerts "Fred"

var differentObj = {};
differentObj.firstName = "Barney";
differentObj.bar = obj.foo; // Not *calling* it, just getting a reference to it
differentObj.bar(); // alerts "Barney"

In fact, foo isn't intrinsically tied to any object at all:

var f = obj.foo; // Not *calling* it, just getting a reference to it
f(); // Probably alerts "undefined"

There, since we didn't call f via an object property, this wasn't explicitly set. When this isn't explicitly set, it defaults to the global object (which is window in browsers). window probably doesn't have a property firstName, and so we got "undefined" in our alert.

There are other ways to call functions and set what this is: By using the function's .call and .apply functions:

function foo(arg1, arg2) {
    alert(this.firstName);
    alert(arg1);
    alert(arg2);
}

var obj = {firstName: "Wilma"};
foo.call(obj, 42, 27); // alerts "Wilma", "42", and "27"

call sets this to the first argument you give it, and then passes along any other arguments you give it to the function it's calling.

apply does exactly the same thing, but you give it the arguments for the function as an array instead of individually:

var obj = {firstName: "Wilma"};
var a   = [42, 27];
foo.apply(obj, a); // alerts "Wilma", "42", and "27"
//             ^-- Note this is one argument, an array of arguments for `foo`

Again, though, there's a lot more to explore about this in JavaScript. The concept is powerful, a bit deceptive if you're used to how some other languages do it (and not if you're used to some others), and worth knowing.

Here are some examples of this not referring to an object in ES5's strict mode:

(function() {
    "use strict";   // Strict mode

    test("direct");
    test.call(5, "with 5");
    test.call(true, "with true");
    test.call("hi", "with 'hi'");

    function test(msg) {
        console.log("[Strict] " + msg + "; typeof this = " + typeof this);
    }
})();

Output:

[Strict] direct; typeof this = undefined
[Strict] with 5; typeof this = number
[Strict] with true; typeof this = boolean
[Strict] with 'hi'; typeof this = string

Whereas in loose mode, all of those would have said typeof this = object; live copy.

T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
  • 0 down vote Here is how i would explain it, simply: this refers to the object that called the function. Since differentObj called foo(), this will point to differentObj. Since f was defined in the global scope, its a method of the window object, so this points to window. Since the window object does not have a property firstName, this.firstName returns undefined Fun fact: anything defined in the global scope, which is the top layer/level, becomes a property of the window object (global scope = window object). – ryanwaite28 Jun 28 '17 at 18:41
  • 2
    @ryanwaite28: *"this refers to the object that called the function"* No, it doesn't. Objects don't call methods, code does; in JavaScript, code is only loosely linked to objects. When code calls methods, it sets the value of `this`, explicitly or implicitly, to whatever it likes -- in strict mode, it may not even be an object reference, it could be a primitive value. – T.J. Crowder Jun 30 '17 at 13:57
  • Crowder technically yes. But for the sake of explaining it in a way people can understand, i said objects. But thanks for add the abstract details. "this" can literally refer to anything. – ryanwaite28 Jun 30 '17 at 15:05
  • @T.J.Crowder can i add edit the snippet and put them in stack snippet ? – brk Apr 19 '18 at 04:40
  • @brk: Do you mean you want to edit the answer to turn the code blocks into runnable snippets? If so: Go for it, and thank you! – T.J. Crowder Apr 19 '18 at 06:50
  • @T.J.Crowder yes i mean that – brk Apr 19 '18 at 07:24
6

The this Keyword

In JavaScript, the thing called this, is the object that "owns" the JavaScript code.

The value of this, when used in a function, is the object that "owns" the function.The value of this, when used in an object, is the object itself. The this keyword in an object constructor does not have a value. It is only a substitute for the new object.The value of this will become the new object when the constructor is used to create an object.

Note that this is not a variable. It is a keyword. You cannot change the value of this.

Naresh Kumar
  • 345
  • 3
  • 6
4

Here is how i would explain it, simply:

this refers to the object that called the function.

so looking at this:

var foo = {
  name: "foo",
  log: function(){
    console.log(this.name);
  }
}

var bar = {
  name: "bar"
}
bar.log = foo.log;
bar.log();

the bar object stores a reference of foo's log method into it's own log property for itself. now when bar calls its log method, this will point to bar because the method was called upon by the bar object.

this works for any other object, even the window object. if you call a function via the global scope, this will point to the window object.

by using the bind or call methods of a function, you can explicitly define what the object this will refer to during execution.

Fun fact: anything defined in the global scope, which is the top layer/level, becomes a property of the window object (global scope = window object).

ryanwaite28
  • 1,143
  • 2
  • 16
  • 33
1

Top Google result for "javascript this": http://www.quirksmode.org/js/this.html

Edit: I think the key sentence is:

"In JavaScript "this" always refers to the “owner” of the function we're executing, or rather, to the object that the function is a method of."

Quirksmode is (generally*) excellent, worth reading the whole article in detail.

*Apparently this statement is not necessarily correct, see T.J. Crowder's comment below.

T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
Richard H
  • 34,219
  • 33
  • 105
  • 133
  • not in javascript.. this in jquery.. thanks anyway! :D – JCm Nov 16 '10 at 16:00
  • 5
    jQuery *is* written in Javascript. Any jQuery code is also Javascript – Gareth Nov 16 '10 at 16:05
  • *"'In JavaScript "this" always refers to the “owner” of the function we're executing, or rather, to the object that the function is a method of.'"* Wow, I hope the rest of the article is better than that. That quote perpetuates a distructive myth, not up to quirksmode's usual standards. – T.J. Crowder Nov 16 '10 at 16:10
  • @T.J.Crowder can you explain the myth or link to more info about you what you mean? – Daniel Sokolowski Oct 13 '16 at 15:32
  • @DanielSokolowski: Two posts on my blog: [*Mythical methods*](http://blog.niftysnippets.org/2008/03/mythical-methods.html) and [*You must remember `this`*](http://blog.niftysnippets.org/2008/04/you-must-remember-this.html). :-) – T.J. Crowder Oct 13 '16 at 16:18
0

The keyword this acts as a placeholder, and will refer to whichever object called that method when the method is actually used in Java Script

Ujjwal-Nadhani
  • 533
  • 2
  • 6
  • 19
-1

Regular functions belong to the class that defines these functions and the same object that invokes the function is passed to the function as the fist parameter and function handle it with this keyword;

When an object is created from a class it contains only a set of properties and there is no function in the object. And the functions belong to the class. however, how is a function called by an object?

Consider the following code.

var obj = {
            p1: 'property 1',

            func1 () {
                return this.p1
            },

            func2 (param) {
                return this.p1 + param
            }
    }

And also call functions by obj object

obj.func1 ();
obj.func2 ('A');

In fact, functions at runtime look like the following

var obj = {
            p1: 'property 1',

            func1 (this) {
                return this.p1
            },

            func2 (this, param) {
                return this.p1 + param
            }
    }

func1 (obj);
func2 (obj, 'A');

With bind method can create a new function that does not belong to class and can set 'this' parameter with a fixed object;

this.func1 = this.func1.bind(aObject)

In arrow functions, this binds to the object that defined the arrow function and that the object passed to the function asthis parameter.

Ali
  • 237
  • 3
  • 9