What is this?
This always refers to and holds the value of an object.
In the browser
console.log(this);

From the browser, this refers to the window object.
'This' in Methods
From a method, this refers to the instance of object which has been created.
classPerson{
constructor(name='Marilyn'){
this.name=name;
}
greeting(){
console.log('hello',this.name);
}
}
constanonymousPerson=newPerson();
constpersonOne=newPerson('Davina');
anonymousPerson.greeting();
personOne.greeting();
//helloMarilyn
//helloDavina
'This' in Functions
From a function, this refers to the value of the object that invoked the function. In the example below, we are runnning our script using Node.js. Scripts run using Node have an object called global as their global object.
constbakeCake=()=>{
returnthis;
}
consttastyCake=bakeCake();
console.log(tastyCake);
//{}
'This' in event handlers
In event handlers, this refers to the value of the element which fired the event.
This element can be an html element such as a button, an anchor link etc
Consider this React component
importReact,{Component}from'react';
classAppextendsComponent{
handleClick=()=>{
console.log(this)
}
render(){
const{profiles}=this.state;
return(
<divclassName="App">
<buttononClick={(event)=>this.handleClick(event)}>Whatisthis?</button>
</div>
)};
}
exportdefaultApp;

This refers to App, which is the dom element which fired the event.
Call, Bind and Apply
Call, bind and applyare JavaScript methods.
Bind
We have already been using the bind method in our examples.
In the example below, we bind 'name' to the instance of the object which is created. This is called implicit binding.
classAnimal{
constructor(name){
this.name=name;
}
}
constbelovedPet=newAnimal('Crookshanks');
console.log(belovedPet.name);
//Crookshanks
We can bind explicitly by using the bind keyword
varmyHouse=function(){
console.log(this.carpetColor);
};
varroomOne={
carpetColor:'grey'
};
varroomTwo={
carpetColor:'cream'
};
myHouse.bind(roomOne);
//atthispoint,myHouseisboundtoroomOnebutthefunctionisnotinvoked.
In the example given above, at the point of line 14, myHouse is bound to roomOne but the function is not invoked. Nothing will be logged to the console.
Call
Call allows you to specify the context of this, and immediately invokes that function.
varmyHouse=function(){
console.log(this.carpetColor);
};
varroomOne={
carpetColor:'grey'
};
varroomTwo={
carpetColor:'cream'
};
myHouse.call(roomOne);
//grey
Apply
Apply works in the same way as call.
The difference between call and apply is that call will accept the first agument to be the context, then the rest of the expected arguments to be passed one by one
Apply expects the first argument to be the context, then the second argument will be an array of the expected arguments.
varmyHouse=function(length,width){
console.log(this.carpetColor);
};
varroomOne={
carpetColor:'grey'
};
myHouse.call(roomOne,2,4);
myHouse.apply(roomOne,[3,6])
//greygrey