Debugging 'this' with Console Logging
You'll learn practical techniques for using console.log() to reveal what this actually points to in different situations.
The Core Technique
When this behaves unexpectedly, the simplest debugging approach is to log it directly. Place console.log(this) at the beginning of any function where you're confused about context. This shows you exactly what object this references at runtime.
function greet() {
console.log('this is:', this);
console.log(this.name);
}
const user = { name: 'Alice', greet };
user.greet(); // logs the user object, then "Alice"
const extracted = user.greet;
extracted(); // logs undefined (strict mode), then error
Strategic Logging Points
Log this at these key moments:
At the call-site:
const callback = obj.method;
console.log('Before call, callback is:', callback);
callback(); // Now check what 'this' became inside
Inside the function:
function process() {
console.log('Inside process, this =', this);
// Rest of your code
}
In chained calls:
const calculator = {
value: 0,
add(n) {
console.log('In add, this =', this);
this.value += n;
return this;
}
};
Compare Definition vs Execution
Log both where you define the method and where you call it to trace how context changes:
const obj = {
method() {
console.log('Call-site this:', this);
}
};
console.log('At definition, obj is:', obj);
setTimeout(obj.method, 100); // Lost context! Logs window/undefined
Key Takeaway: Console logging this at strategic points—especially at call-sites and function entry—reveals exactly how context binding works and why it sometimes surprises you.