Once you know the concept then you would say the same. Yes. There are several cases around this
. Hence by knowing all those scenarios you will be cleared. We are generally afraid out of imagination. Let's not simply imagine instead do some practice.
Hence let's look into the scenarios where and when we should ideally use this
and what its importance in its scope with different possible examples.
So, basically what this
actually refers to in Javascript?
It refers to an object
in javascript. Based on the usage of this
its reference will be changed. So, if you got all those references then you are done.
I hope this introduction would be fine. OK. Let's decipher this
now:
Before entering into explanation I want to give a summary here:
S.No. | Scenario | `this` refers to |
1. | Inside object | Refers to parent object only |
2. | Inside browser window | Refers to the window object |
3. | Strict mode in the browser window | Refers to the window object |
4. | Inside function | Refers to the window object |
5. | strict mode: Inside function | Returns undefined |
6. | In Event handler | Refers HTML Element |
7. | Using with call(), bind() and apply() | Refers to objects sent as arguments |
8. | Inside JS classes | Refers to the current object. |
9. | In arrow function | Refers to the window object. |
1. Inside object
Refers to parent object only.
Example:
const testObj = {
firstName: 'John',
lastName: 'Carter',
name: function name() {
return this.firstName + " " + this.lastName; // Here this refers to `testObj`
}
}
console.log(testObj.name());
> John Carter
2. Alone using this
1. Inside browser window
Refers to the window object.
Hence window methods like alert, atob, blur
etc. are accessed using this.
Example:
Access thealert
function of the window object using this.
Example:
2. Strict mode in the browser window
Also this
refers to the window object.
Example:
3. Inside function
Also this
refers to the window object
Example:
Using strict mode returns undefined.
function thisInsideFunction() {
'use strict'; // see strict mode
return this;
}
console.log(thisInsideFunction());
> undefined
4. In Event handler
Users can trigger click, enter, keydown events on various form elements in HTML from the browser. While handling those events we bind those event handlers with functions generally. If we pass this from the handler then it refers to the corresponding HTML element
object.
Example:
<button onclick="buttonClick(this)">Submit</button>
// this refers to button HTMLElement here.
5. Using with call(), bind() and apply() methods
These are javascript built-in methods. call() & apply() used to call object method of other object using another object as an argument.
Complete article on these methods are here
Whereas bind borrows object method of another object and creates a new object altogether.
Essentially, all these three things will do a similar kind of work.
now, what this
refers to in these methods. It refers to objects sent as arguments.
Example
const testObj = {
firstName: 'John',
lastName: 'Carter',
name: function name() {
return this.firstName + " " + this.lastName;
}
}
const anotherObj = {
firstName: 'new john',
lastName: 'Carter'
}
console.log(testObj.name.apply(anotherObj)); // this refers to anotherObj
> new john Carter
Same in case of call & bind as well.
6. Inside JS classes
this
refers to the current object.
Example
class TestThis {
a;
b;
normalFunction() {
console.log('normal function');
console.log(this);
}
static staticFunction() {
console.log('Static function');
}
}
const test = new TestThis();
test.normalFunction();
Note that static properties are not part of this
.
7. this
in arrow function
Refers to the window object.
inside object method refers to the parent obj.
let testObj = {
test: 10,
bar: function() {
let x = (() => this);
return x;
}
};
console.log(testObj.bar()());
I covered most possible cases of this. Please let me know by commenting if you come across any new scenarios.
Also, do comment if you don't understand any scenario.
Top comments (6)
My name is Peter, I am web developer and I don't use this 2 years long.
... because I am prefered functional programming. Any way I am faced
this
question under my hiering process so many times.I would say that this is easy only for arrow functions=)
Actually, not only for event handlers, but for some other APIs (e.g. setTimeout) where you pass a callback this may be set by own rules (I have a small post about that)
this
in an arrow function is whatever it was in the outer context - not always thewindow
.True. I mentioned the same. Please read complete 7th point.
Thanks.
Your table (which appears to have broken formatting) has 9 scenarios, and there are only 7 numbered scenarios in the main text. I think there are some MD formatting issues to sort out.
I covered two scenarios inside. Please go through whole article.
Thank you.