This Keyword:-
It is an Object, that is executing the current function.
But, this keyword behaviour is different in different situations.
1. Global Space :- this keyword will always point to the global window object in global space.
console.log(this); //global window object
2. Normal Function:- If we wrote the normal function in global space, that function will always point to the window object, so if we print "this" inside a function. that will always be widow object.
function User() {
console.log(this) //global window object
}
User();
3. Objects:- If we consider an object, functions inside the object will always have the parent. so "this" will not point to the global object. instead of that, it will point the particular object.
const data = {
name: 'uma',
age: 22,
address: function() {
console.log(this.age) //22
}
}
data.address()
Note:- But Arrow Function will always point to the window object.
const data = {
name: 'uma',
age: 22,
address: () => {
console.log(this.age) //undefined
}
}
data.address()
4. Constructor:- Constructor also have the same behaviour as Objects. it will also point to the particular object.
function User(name) {
this.name = name,
console.log(this.name) //uma
}
const user1 = new User('uma')
Thanks for reading!
Top comments (1)
False/ misleading: what this refers to doesn't depend on where it's used but rather on how it's called (aka its call-site). I recommend you check out the you don't know JavaScript book.
Some comments have been hidden by the post's author - find out more