Home  >  Article  >  Web Front-end  >  How Does the \"this\" Keyword Behave in jQuery and JavaScript?

How Does the \"this\" Keyword Behave in jQuery and JavaScript?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-26 19:41:29348browse

How Does the

What Does "this" Mean in jQuery?

In jQuery, "this" represents the DOM element that is the subject of the function being called. This is commonly used in event callbacks and functions that act on multiple elements. For instance:

<code class="javascript">$("div").click(function() {
  this.style.color = "red";
});</code>

This sets the foreground color of the clicked element to red.

Generically in JavaScript

In JavaScript, "this" refers to the object that is calling the function. This is determined by how the function is called, rather than where it is defined.

<code class="javascript">var obj = {
  firstName: "Fred",
  foo: function() {
    alert(this.firstName);
  }
};

obj.foo(); // alerts "Fred"</code>

In this example, "this" is set to obj when foo is called. However, the value of "this" can be any object, including the global object (window in browsers).

<code class="javascript">f(); // Probably alerts "undefined"

//... Later

var obj = {
  firstName: "Wilma"
};

f = obj.foo;
f(); // alerts "Wilma"</code>

In the above example, f is a reference to the foo function. When f is called without an object property, "this" defaults to the global object.

ES5 Strict Mode

In ES5 strict mode, "this" can have any value, including non-objects. If "this" is not explicitly set, it defaults to undefined.

<code class="javascript">"use strict";

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

test(); // typeof this = undefined
test.call(5); // typeof this = number</code>

In regular (non-strict) mode, all of these calls would have returned typeof this = object.

The above is the detailed content of How Does the \"this\" Keyword Behave in jQuery and JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn