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

🚀 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 ofuser
.Inside
greet
, thethis
keyword refers to the object (user
) on which the method is called.
🧠 How this
Works in Methods
When you call
obj.method()
, JavaScript setsthis
toobj
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
Define an object
book
with atitle
property and adescribe()
method that logs the title usingthis
.Add a method to an object after its creation that prints a message using
this
.Rewrite a method using arrow function — observe and explain what breaks.
🟡 Intermediate Challenges
Create a shared function
announce
and assign it as a method to two objects. Show howthis
behaves.Create a method that uses
setTimeout
inside. Demonstrate both broken and fixed versions using arrow functions.Write a constructor function that assigns a method inside the object and uses
this
.
🔴 Advanced Challenges
Simulate a DOM-like event handler that loses
this
context and fix it using.bind
.Build a method-chaining counter object (like a jQuery-style plugin).
Implement a clone method that returns a shallow copy of the object with all method bindings preserved.
Use a proxy to intercept calls to methods and log
this
before delegating the call.
🧠 Bonus Aha! Challenge
- 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 isthis
If not →
this
isundefined
in strict mode, orwindow
otherwise
🧠 Analogy
Think of
this
as “who called me?”
- Like answering a phone: whoever is on the line becomes
this
.
🧾 Cheatsheet
How it's Called | What this is |
obj.method() | obj |
func() (strict mode) | undefined |
func() (non-strict) | window |
Arrow Function | Lexically inherited |
.call(obj) | Explicitly set to obj |
.bind(obj) | Permanently set to obj |
Constructor with new | New 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:
Create
stepTracker
object with propertystep = 0
Add
up()
,down()
, andstatus()
methodsEach method should
return this
to allow chainingstatus()
logs the current step
➕ Bonus:
Add
reset()
Add
max
andmin
step limitsTrack 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 methodsNot 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.
Subscribe to my newsletter
Read articles from manoj ymk directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
