Lesson 31: Mastering JavaScript Object Methods and this concept with challenges!

manoj ymkmanoj ymk
6 min read

🚀 What Are Object Methods?

An object method is a function stored as a property on an object — a way for objects to perform actions.

let user = {
  name: "Alice",
  greet() {
    console.log(`Hi, I'm ${this.name}`);
  }
};

user.greet(); // "Hi, I'm Alice"

In this example:

  • greet is a method of user.

  • Inside greet, the this keyword refers to the object (user) on which the method is called.

🧠 How this Works in Methods

  • When you call obj.method(), JavaScript sets this to obj at runtime.

  • It doesn’t matter where the method was defined — it only matters how it was called.

let admin = user;
admin.greet(); // "Hi, I'm Alice"

📝 Method Shorthand

let obj = {
  method() { return true; }
};

This is syntactic sugar for:

let obj = {
  method: function() { return true; }
};

⚠️ Arrow Functions and this

Arrow functions do not have their own this. They lexically bind this from the outer scope.

let user = {
  name: "Alex",
  sayHi() {
    const arrow = () => console.log(this.name);
    arrow(); // Works: uses `this` from sayHi()
  }
};

🔹 2. Fill Any Gaps

🔍 What’s NOT in Your Notes — But You Must Know

this Is Not Bound to the Object at Definition

let obj = {
  method: function() {
    console.log(this);
  }
};

let fn = obj.method;
fn(); // `this` is undefined in strict mode!

🔥 Strict Mode Behavior

In non-strict mode, this defaults to the window (global object). In strict mode, this becomes undefined in standalone functions.

"use strict";
function f() {
  console.log(this); // undefined
}

🧪 this in Callbacks Can Be a Trap

let user = {
  name: "Luna",
  greet() {
    setTimeout(function() {
      console.log(this.name); // undefined or window.name
    }, 1000);
  }
};

✅ Fix with arrow function or .bind(this):

setTimeout(() => console.log(this.name), 1000);

🌀 The this Trap in Object Literals

function makeUser() {
  return {
    name: "John",
    ref: this  // ← `this` is evaluated in makeUser context (likely undefined)
  };
}

this inside an object literal does not refer to the object being created.

📌 Method Chaining Requires Returning this

let obj = {
  value: 0,
  increment() {
    this.value++;
    return this;
  }
};
obj.increment().increment(); // works

🔹 3. Challenge Me Deeply

🟢 Basic Challenges

  1. Define an object book with a title property and a describe() method that logs the title using this.

  2. Add a method to an object after its creation that prints a message using this.

  3. Rewrite a method using arrow function — observe and explain what breaks.

🟡 Intermediate Challenges

  1. Create a shared function announce and assign it as a method to two objects. Show how this behaves.

  2. Create a method that uses setTimeout inside. Demonstrate both broken and fixed versions using arrow functions.

  3. Write a constructor function that assigns a method inside the object and uses this.

🔴 Advanced Challenges

  1. Simulate a DOM-like event handler that loses this context and fix it using .bind.

  2. Build a method-chaining counter object (like a jQuery-style plugin).

  3. Implement a clone method that returns a shallow copy of the object with all method bindings preserved.

  4. Use a proxy to intercept calls to methods and log this before delegating the call.

🧠 Bonus Aha! Challenge

  1. What does this print and why?
let obj = {
  method: () => console.log(this)
};
obj.method();

🔹 4. Interview-Ready Questions

🔍 Concept-Based

  • What’s the difference between a function and a method in JavaScript?

  • How is this determined in JavaScript functions?

📘 Scenario-Based

  • You assign a method from one object to another. What happens to this?

  • What’s the difference in this behavior between arrow functions and regular functions?

  • Explain what happens here:

let obj = {
  value: 42,
  getValue: function() {
    return this.value;
  }
};
let get = obj.getValue;
console.log(get()); // ?

🛠 Debugging Challenge

A dev reports that their object method logs undefined instead of the expected name. What could be going wrong?

✅ Best Practices

  • Use arrow functions in callbacks to preserve lexical this.

  • Avoid using this in object literals outside methods.

  • Prefer method chaining in fluent APIs (e.g., jQuery, Lodash chains).

🚫 Red Flags

  • Using arrow functions as methods (obj = { method: () => this.name }) — doesn’t work.

  • Forgetting .bind(this) in callback-heavy contexts.


🔹 5. Real-World Usage

💻 Frontend Frameworks

  • React: this used in class components (rare now, but useful historically).

  • jQuery: Chainable APIs (returning this).

  • Vue 2: Uses this extensively for data access in component methods.

🧩 Libraries

  • Lodash chaining: _.chain(obj).map().filter().value()

  • Express middleware patterns often use .use().get().post() chaining.

🧪 Production Example

// Chaining in jQuery
$('#button')
  .addClass('active')
  .fadeIn()
  .on('click', function() {
    console.log(this); // DOM element
  });

🔹 6. Remember Like a Pro

🔑 Mnemonic for this

"DOT = this owns the object"

  • If dot is used → the object before the dot is this

  • If not → this is undefined in strict mode, or window otherwise

🧠 Analogy

Think of this as “who called me?

  • Like answering a phone: whoever is on the line becomes this.

🧾 Cheatsheet

How it's CalledWhat this is
obj.method()obj
func() (strict mode)undefined
func() (non-strict)window
Arrow FunctionLexically inherited
.call(obj)Explicitly set to obj
.bind(obj)Permanently set to obj
Constructor with newNew instance object

🔹 7. Apply It in a Fun Way

🛠 Mini Project: Fluent-style Step Tracker

Build a chainable stepTracker object like:

stepTracker
  .up()
  .up()
  .down()
  .status(); // logs: "You're on step 1"

🔨 Steps:

  1. Create stepTracker object with property step = 0

  2. Add up(), down(), and status() methods

  3. Each method should return this to allow chaining

  4. status() logs the current step

➕ Bonus:

  • Add reset()

  • Add max and min step limits

  • Track history of all moves in an array


🧠 (Optional Extra Value)

✅ Used Heavily In:

  • Vue 2: All component methods rely on this

  • React class components: this.state, this.setState

  • jQuery, Lodash: Method chaining

❌ Common Mistakes

  • Using this in arrow function methods

  • Not binding callbacks in class constructors

  • Forgetting strict mode rules for this

⚡ Performance Tips

  • Don’t overuse .bind() in render loops — can hurt performance.

  • Prefer arrow functions in closures (like event listeners or timers) if this should be lexical.

0
Subscribe to my newsletter

Read articles from manoj ymk directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

manoj ymk
manoj ymk