JS ObjectsLesson #53
JavaScript this Keyword
The this keyword refers to an object.
this in Objects
The this keyword refers to an object.
In JavaScript, this is used to access the object that is calling a method.
this in an Object Method
When used inside an object method, this refers to the object.
Example
Example Code
javascriptconst person = {
firstName: "John",
lastName: "Doe",
age: 50,
fullName: function() {
return this.firstName + " " + this.lastName;
}
};In the example above:
- this.firstName refers to the firstName property of the person object
- this.lastName refers to the lastName property of the person object
Why Use this?
The this keyword makes it possible to use the same method with different objects.
Example
Example Code
javascriptconst person1 = {
name: "John",
hello: function() {
return "Hello " + this.name;
}
};
const person2 = {
name: "Anna",
hello: function() {
return "Hello " + this.name;
}
};
document.getElementById("demo").innerHTML = person1.hello();this Alone
When used alone, this refers to the global object.
In a browser, the global object is the window object.
Example
Example Code
javascriptlet x = this;
document.getElementById("demo").innerHTML = x;In strict mode, this is undefined when used alone.
this in a Function
In a regular function, this also refers to the global object.
Example
Example Code
htmlfunction myFunction() {
return this;
}
document.getElementById("demo").innerHTML = myFunction();Summary
- In an object method, this refers to the object
- this lets methods access object properties
- Used alone, this refers to the global object
See Also:
> What are JavaScript Objects?
> What are Object Properties?
> What are Object Methods?
> How to Display JavaScript Objects
> What is an Object Constructor?
Advanced Chapters:
> JavaScript Object Definitions
> JavaScript Object Advanced this
> JavaScript Object Iterations
> JavaScript Object Getters & Setters
> JavaScript Object Management
> JavaScript Object Protection
> JavaScript Object Prototypes
> JavaScript Object Reference
Interactive Code Examples
JS Example 1
javascriptJavaScript syntax and algorithm demonstration.
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
fullName: function() {
return this.firstName + " " + this.lastName;
}
};JS Example 2
javascriptInteractive runnable JavaScript example from EA Academy.
Live Output Preview:
JS Example 3
javascriptInteractive runnable JavaScript example from EA Academy.
Live Output Preview:
JS Example 4
htmlJavaScript syntax and algorithm demonstration.
function myFunction() {
return this;
}
document.getElementById("demo").innerHTML = myFunction();