JavaScript Object Methods & this
Keyword
In JavaScript, methods are functions inside objects that perform actions on the object’s data. The special keyword this
refers to the object that calls the method.
1️⃣ Defining Object Methods
An object method is a function assigned to a property in an object.
📌 The function fullName()
is a method of the person
object.
📌 this.firstName
refers to person.firstName
.
2️⃣ The this
Keyword
What is this
?
The this
keyword refers to the object that the method is called on.
Example: Using this
in an Object
📌 this.brand
refers to car.brand
, and this.model
refers to car.model
.
3️⃣ this
in Different Contexts
✅ Inside an Object Method
this
refers to the current object.
❌ Alone (Global Scope)
this
refers to the global object (window
in browsers, global
in Node.js).
❌ Inside a Regular Function
By default, this
is undefined
in strict mode or points to the global object.
✅ Inside an Arrow Function
Arrow functions do not have their own this
. They inherit this
from their surrounding scope.
📌 Solution: Use regular functions inside objects.
4️⃣ Using this
in Constructors
Constructors are used to create multiple objects with the same structure.
📌 this.name
refers to the new object created.
5️⃣ this
in setTimeout
By default, this
in setTimeout
refers to the global object.
✅ Fix: Use an Arrow Function (inherits this
from surrounding scope).
6️⃣ Object Method Shorthand (ES6)
Instead of writing function
, use method shorthand.
7️⃣ Borrowing Methods
You can borrow methods from other objects using call()
, apply()
, or bind()
.
📌 call()
allows you to manually set this
.
🎯 Summary
✅ Object methods → Functions inside objects
✅ this
refers to the calling object
✅ Arrow functions don't have their own this
✅ Use this
carefully in constructors & setTimeout
✅ Method shorthand (ES6) is cleaner
✅ Methods can be borrowed using call()
, apply()
, bind()
🚀 Now you're an expert in object methods and this
! Let me know if you need more examples. 😊