JavaScript Object Methods & this Keyword

JavaScript Object Methods & this Keyword

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.

const person = { firstName: "John", lastName: "Doe", fullName: function() { return this.firstName + " " + this.lastName; } }; console.log(person.fullName()); // Output: "John Doe"

📌 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

const car = { brand: "Toyota", model: "Corolla", getDetails: function() { return `Car: ${this.brand} ${this.model}`; } }; console.log(car.getDetails()); // Output: "Car: Toyota Corolla"

📌 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.

const user = { name: "Alice", greet: function() { return `Hello, ${this.name}!`; } }; console.log(user.greet()); // Output: "Hello, Alice!"

Alone (Global Scope)

this refers to the global object (window in browsers, global in Node.js).

console.log(this); // In browser: window object

Inside a Regular Function

By default, this is undefined in strict mode or points to the global object.

function show() { console.log(this); } show(); // In strict mode: undefined, otherwise window/global

Inside an Arrow Function

Arrow functions do not have their own this. They inherit this from their surrounding scope.

const obj = { name: "Emma", greet: () => { console.log(this.name); // ❌ Undefined (Arrow functions don't have their own `this`) } }; obj.greet();

📌 Solution: Use regular functions inside objects.

4️⃣ Using this in Constructors

Constructors are used to create multiple objects with the same structure.

function Person(name, age) { this.name = name; this.age = age; this.introduce = function() { return `Hi, I'm ${this.name}, ${this.age} years old.`; }; } const john = new Person("John", 25); console.log(john.introduce()); // Output: "Hi, I'm John, 25 years old."

📌 this.name refers to the new object created.

5️⃣ this in setTimeout

By default, this in setTimeout refers to the global object.

const person = { name: "Tom", greet: function() { setTimeout(function() { console.log(this.name); // ❌ Undefined (this refers to window) }, 1000); } }; person.greet();

Fix: Use an Arrow Function (inherits this from surrounding scope).

const personFixed = { name: "Tom", greet: function() { setTimeout(() => { console.log(this.name); // ✅ Correctly logs "Tom" }, 1000); } }; personFixed.greet();

6️⃣ Object Method Shorthand (ES6)

Instead of writing function, use method shorthand.

const dog = { name: "Buddy", bark() { return `${this.name} says Woof!`; } }; console.log(dog.bark()); // Output: "Buddy says Woof!"

7️⃣ Borrowing Methods

You can borrow methods from other objects using call(), apply(), or bind().

const user1 = { name: "Alice" }; const user2 = { name: "Bob" }; function sayHi() { return `Hi, ${this.name}`; } console.log(sayHi.call(user1)); // Output: "Hi, Alice" console.log(sayHi.call(user2)); // Output: "Hi, Bob"

📌 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. 😊

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close