Understanding "this" in jQuery and JavaScript
"this" is a highly versatile keyword in JavaScript and jQuery. Its meaning varies depending on the context in which it's used.
"this" in jQuery
In jQuery, "this" typically refers to the DOM element being manipulated by the function being called. For example, in an event callback handler:
$("div").click(function() { // Here, "this" refers to the DOM element for the clicked div. this.style.color = "red"; });
"this" in JavaScript
In JavaScript, the meaning of "this" is determined by the call context (not the definition context):
var obj = { foo: function() { alert(this.firstName); }, firstName: "Fred" };
function foo() { alert(this.firstName); }
foo.call(obj, 42, 27);
foo.apply(obj, [42, 27]);
Special considerations:
The above is the detailed content of How does 'this' behave differently in jQuery and JavaScript?. For more information, please follow other related articles on the PHP Chinese website!