This in JavaScript
To access the object, a method can use this keyword
The value of this is the object “before dot”, the one used to call the method.
It also behaves differently in strict mode and non strict mode.
- this in a Method: in an object method, this refers to the “owner” of the method.
const me = {
stName: ‘hema’,
ndName: ‘kun’,
fullName: function(){
return’${this.stName} ${this.ndName}’
}
}
console.log(me.fullName())
- this refers to me object , because the me object “owns” the fullName method.
2 . this Alone: When used alone, the owner is the global object, so this refers to the Global object.
let thisAlone = this
//In a browser window
console.log(this); //refers to the window object
3.this in a function: Inside function the value of this depends on how the function is being called.
In function, this refers to the global object[object window].
function test(){
return this
}
test() //[object window]
4.this in Function ‘strict mode’
JavaScript strict mode does not allow default binding.
When used in a function, in strict mode, this is undefined.
“use strict”
function test(){
return this
}
test() //undefined.
5.Inside Arrow Function
Arrow function are special they do not have their own this
In arrow functions this retains the value of enclosing lexical context this
let user = {
firstName: “Joe”,
sayHi(){
let arrow=()=>alert(this.firstName);
arrow();
}
};
user.sayHi();
This is the special feature of arrow function. This is useful when we don not want to have separate this but want to take from outer context.