Discover how a single word, <code>this</code>, can make your code smarter and simpler!
Why this in functions in Javascript? - Purpose & Use Cases
Imagine you have many buttons on a webpage, and you want each button to show its own label when clicked. Without a way to refer to the button itself inside the click code, you'd have to write separate code for each button manually.
Writing separate code for each button is slow and boring. If you add more buttons, you must write even more code. It's easy to make mistakes, like showing the wrong label or forgetting to update some buttons.
The this keyword inside functions lets you refer to the object that called the function. This means one function can work for many buttons, each knowing which one was clicked, without extra code.
button1.onclick = function() { alert('Button 1'); };
button2.onclick = function() { alert('Button 2'); };function showLabel() { alert(this.label); }
button1.label = 'Button 1';
button2.label = 'Button 2';
button1.onclick = showLabel;
button2.onclick = showLabel;Using this makes your code flexible and reusable, so one function can handle many objects easily.
When you click on different items in a menu, each item can show its own details using the same function that uses this to know which item was clicked.
this helps functions know who called them.
It saves time by avoiding repeated code for similar tasks.
It makes your code easier to manage and less error-prone.
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
