Access This In JavaScript


How to access this inside callback in JavaScript ? How to access this inside forEach in JavaScript ?

Access this inside callback

There are couple of ways to access this inside a callback function. Let’s first write some code which makes use of callbacks. I’m going to use forEach method to iterate over an array.

function DataModule(){
	this.multiplier= 2;
  
	this.alterData = function(dataArr){
	  	dataArr.forEach(function(data, index){
	    	dataArr[index] = data * 2;
	    })
	    return dataArr;
	  }
}

let obj = new DataModule();
console.log(obj.alterData([1,2,3]));

// output -   [2, 4, 6]

Now let’s use the multiplier from this using variable multiplier.

function DataModule(){
	this.times = 2;
  
	this.alterData = function(dataArr){
	  	dataArr.forEach(function(data, index){
	    	dataArr[index] = data * this.times;
	    })
	    return dataArr;
	  }
}

let obj = new DataModule();
console.log(obj.alterData([1,2,3]));

// Outputs : -  [NaN, NaN, NaN]

This happens because this.times is undefined inside the callback method.

Access this Using Arrow function

You can access the this context inside the forEach using arrow functions. Modify the code as shown:

function DataModule(){
	this.times = 2;
  
	this.alterData = function(dataArr){
	  	dataArr.forEach((data, index) => {
	    	dataArr[index] = data * this.times;
	    })
	    return dataArr;
	  }
}

let obj = new DataModule();
console.log(obj.alterData([1,2,3]));

//   [2, 4, 6]

Access this Using bind

You can also use bind method to bind the context to the callback function.

function DataModule(){
	this.times = 2;
  
	this.alterData = function(dataArr){
	  	dataArr.forEach(function(data, index){
	    	dataArr[index] = data * this.times;
	    }.bind(this))
	    return dataArr;
	  }
}

let obj = new DataModule();
console.log(obj.alterData([1,2,3]));

Passing this to forEach method

forEach method provides an optional parameter to pass the scope.

function DataModule(){
	this.times = 2;
  
	this.alterData = function(dataArr){
	  	dataArr.forEach(function(data, index){
	    	dataArr[index] = data * this.times;
	    },this);
	    return dataArr;
	  }
}

let obj = new DataModule();
console.log(obj.alterData([1,2,3]));