JavaScript this Keyword
In object-oriented languages, this represents a reference to the current object.
But in JavaScript, this is not fixed; it changes with the execution environment.
- In a method, this refers to the object that owns the method.
- If used alone, this refers to the global object.
- In a function, this refers to the global object.
- In a function, in strict mode, this is undefined.
- In an event, this refers to the element that receives the event.
- Methods like call() and apply() can bind this to any object.
Examples
Try it Yourself »
this in Methods
In an object method, this points to the object that calls the method in which it resides.
In the example above, this represents the person object.
The object that owns the fullName method is person.
Using this Alone
When using this alone, it points to the global object.
In a browser, window is the global object [object Window]:
In strict mode, if used alone, this also points to the global object.
Using this in Functions (Default)
In a function, the owner of the function is bound to this by default.
In a browser, window is the global object [object Window]:
Using this in Functions (Strict Mode)
In strict mode, the function is not bound to this, and at this time this isundefined。
this in Events
In HTML event handlers, this points to the HTML element that receives the event:
Examples
Try it Yourself »
Binding in Object Methods
In the following example, this is the person object; the person object is the owner of the function:
Examples
Try it Yourself »
Examples
Try it Yourself »
Explanation:this.firstNamerepresentsthisthe (person) object'sfirstNameproperty.
Explicit Function Binding
In JavaScript, functions are also objects; objects have methods, and apply and call are methods of function objects. These two methods are extremely powerful; they allow switching the execution context of a function, i.e., the object to which this is bound.
In the following example, when we use person2 as an argument to call the person1.fullName method,thisthis will point to person2, even though it is a method of person1:
Examples
Try it Yourself »