The this keyword helps you access the object that owns the current function. It lets functions know who called them.
this in functions in Javascript
function example() { console.log(this); }
Inside a regular function, this usually refers to the object that called the function.
In the global scope or simple function calls, this can be undefined in strict mode or the global object otherwise.
this inside greet refers to obj, so it prints 'Alice'.const obj = { name: 'Alice', greet: function() { console.log(this.name); } }; obj.greet();
showThis as a simple function prints undefined in strict mode or the global object otherwise.function showThis() { console.log(this); } showThis();
greetFunc is called without an object, so this is undefined and this.name is undefined.const person = { name: 'Bob', greet() { console.log(`Hello, ${this.name}`); } }; const greetFunc = person.greet; greetFunc();
This program shows how this inside sayName refers to the user object, so it prints the user's name.
const user = { name: 'Emma', sayName: function() { console.log(`My name is ${this.name}`); } }; user.sayName();
Arrow functions do not have their own this. They use this from the surrounding code.
Using this inside event handlers or callbacks can behave differently depending on how the function is called.
this points to the object that calls the function.
Inside object methods, this helps access object properties.
Be careful: calling a function without an object can make this undefined.
Practice
this refer to inside a regular function called as obj.method()?Solution
Step 1: Understand how
When a function is called as a method of an object,thisworks in method callsthispoints to that object.Step 2: Apply to the example
Sinceobj.method()methodis called byobj,thisinsidemethodrefers toobj.Final Answer:
The objectobjthat calls the method -> Option DQuick Check:
obj.method()meansthis = obj[OK]
this is the caller object in method calls [OK]- Thinking
thisis always global - Confusing
thiswith the function itself - Assuming
thisis undefined in method calls
this refers to the object?Solution
Step 1: Understand function types and
Arrow functions do not have their ownthisthis; they inherit from the outer scope. Regular functions have their ownthis.Step 2: Check each option
A uses arrow function, sothisis inherited from outer scope (global), not the object. B uses concise method syntax, which bindsthisto the object. C uses invalid syntax (cannot define concise method with arrow). D uses invalid syntax (function() =>not valid).Final Answer:
const obj = { method() { console.log(this); } }; -> Option CQuick Check:
Use concise method syntax for object methods [OK]
this in objects [OK]- Using arrow functions for object methods expecting
thisas object - Attempting invalid concise arrow syntax like
method() => {} - Using invalid syntax like
function() => {}inside object
const obj = {
name: 'Alice',
greet() {
function inner() {
console.log(this.name);
}
inner();
}
};
obj.greet();Solution
Step 1: Analyze
The functionthisinsideinnerfunctioninneris a regular function called without an object, sothisinside it is undefined in strict mode (or global object in non-strict).Step 2: Check what
Sincethis.nameprintsthisis undefined,this.nameisundefined, soconsole.logprintsundefined.Final Answer:
undefined -> Option AQuick Check:
Inner function called alone:this = undefined[OK]
this undefined [OK]- Assuming
thisinside inner function is the object - Expecting 'Alice' to print
- Confusing arrow functions with regular functions
this.name inside inner refers to obj.const obj = {
name: 'Bob',
greet() {
function inner() {
console.log(this.name);
}
inner();
}
};
obj.greet();Solution
Step 1: Understand why
Becausethisis wrong insideinnerinneris a regular function called alone,thisis undefined, notobj.Step 2: Explore fixes to bind
Changethiscorrectlyinnerto an arrow function: Using arrow function forinnerinheritsthisfromgreet, which isobj. Bindinnertothisusinginner.bind(this)(): Usinginner.bind(this)()explicitly setsthistoobj. Assignconst self = thisand useself.nameinsideinner: Savingthisinselfand usingself.nameworks becauseselfis accessible insideinner.Step 3: Conclusion
All three methods correctly fix the problem.Final Answer:
All of the above -> Option BQuick Check:
Bind or arrow or self variable fixesthis[OK]
this in inner functions [OK]- Only trying one fix and missing others
- Not understanding arrow functions inherit
this - Forgetting to call
bindmethod
counter with a method count that increases a number every second and logs it using this.value. Which code correctly keeps this referring to counter inside setInterval callback?const counter = {
value: 0,
count() {
setInterval(function() {
this.value++;
console.log(this.value);
}, 1000);
}
};
counter.count();Solution
Step 1: Identify the problem with
The callback function is a regular function, sothisinsetIntervalthisinside it is notcounterbut undefined or global object.Step 2: Explore solutions to keep
Replace the callback with an arrow function:thisascountersetInterval(() => { this.value++; console.log(this.value); }, 1000);: Arrow functions inheritthisfromcount, sothis.valueworks. Bindthisto the callback:setInterval(function() { ... }.bind(this), 1000);: Usingbind(this)explicitly setsthisinside callback. Saveconst self = thisbeforesetIntervaland useself.valueinside callback: Savingthisinselfand usingself.valueworks becauseselfis accessible inside callback.Step 3: Conclusion
All three methods correctly keepthisreferring tocounter.Final Answer:
All of the above -> Option AQuick Check:
Arrow, bind, or self variable all fixthisin callbacks [OK]
this in callbacks [OK]- Using regular function without binding
this - Expecting
thisto becounterautomatically - Not saving
thisbefore callback
Ready to prove it?
Pass the test and this pattern moves unknown
