What is this
?
The JavaScript this
keyword refers to the object it belongs to. You have seen in the object which contains any function in it. In that, you have seen that they used this
keyword. This blog post is going to look at what this
means and how its meaning changes depending on where it is used.
Let's now learn in How this
keyword has different values depending on where it is used:
How this
work in a Method?
In an object method, this
refers to the "owner" of the method.
In the below example you can see, this
refers to the user object.
The user object is the owner of the sayHello method.
let user = {
name : "JON SNOW",
msg : "Hello",
sayHello : function() {
console.log (`${this.msg}, ${this.name}`);
}
}
user.sayHello();
Note: The syntax used in the console.log()
function is what's known as Template Literals, and you can read more about this here.
Copy the above code into your browser console and see what happens. You should get an output of something like Hello, JON SNOW
.
Here we can see that sayHello()
is a method of the user
object. Inside the sayHello()
function this
refers to the object that contains it, which in this case is the user
object. The above code would output msg and name
to the console. It's worth noting that we could equally have written console.log(user.msg, user.name)
and received the same output. If we were to create more instances of the user
object, each with different name
and msg
properties, this
is useful for pointing to the specific instance of that user
object.
How this
work in an Alone?
When used alone, the owner is the Global object, so this
refers to the Global object.
In a browser window the Global object is [object Window]
:
var name = this;
console.log (name);
Copy the above code into your browser console and see what happens. You should get an output of something like [object Window]
.
In strict mode, when used alone, this
also refers to the Global object [object Window]
:
"use strict";
var name = this;
console.log (name);
How this
work in a Function?
In a JavaScript function, the owner of the function is the default binding for this
.
So, in a function, this
refers to the Global object [object Window]
.
function user() {
console.log(this) ;
}
user();
Copy the above code into your browser console and see what happens. You should get an output of something like [object Window]
.
JavaScript strict mode does not allow default binding.
So, when used in a function, in strict mode, this
is undefined
.
"use strict";
function user() {
console.log(this) ;
}
user();
For Further Reading
This blog post references some material that can be found in JavaScript & MDN. For further notes on this topic and all things JavaScript, I recommend this resource MDN.
If you found this article useful, let me know on - Ankit Bajpai