Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to function call using 'this' inside forEach loop

In the following object, I have a problem using the 'this' reference:

function SampleObject(){     this.addObject = function(object){...}     ...     // more code here     ...     this.addNewObjects= function(arr){         arr.forEach( function (obj) {             this.addObject(new Obj(obj.prop1, obj.prop2));         });     } } 

I'm assuming the context is changing and that 'this' refers the iterated 'obj', and not 'SampleObject'. I've solved the problem using a normal for loop however, i'm curuois to why this is not working, and would like to know if there is another way to do this.

like image 500
user3339411 Avatar asked Apr 14 '15 11:04

user3339411


People also ask

Is forEach a callback function?

The forEach() method calls a specified callback function once for every element it iterates over inside an array.

Can we use for loop inside forEach loop?

Your for() isn't needed since foreach() already create a loop, you just have to use this loop to increment a value (here called $i) then display it. parsing HTML through PHP is an overhead. You can simply embed PHP into HTML.


2 Answers

You can store this in variable:

var self = this; this.addNewObjects = function(arr){     arr.forEach(function(obj) {         self.addObject(new Obj(obj.prop1, obj.prop2));     }); } 

or use bind:

this.addNewObjects = function(arr) {     arr.forEach(function(obj) {         this.addObject(new Obj(obj.prop1, obj.prop2));     }.bind(this)); } 

And side note, without those this will be window object not obj. This is always object that was created using new keyword or window object if it's normal function. In strict mode this will be undefined in this case.

UPDATE: and with ES6 you can use arrow function:

this.addNewObjects = function(arr) {     arr.forEach((obj) => {         this.addObject(new Obj(obj.prop1, obj.prop2));     }); } 

arrow functions don't have their own this and they get it from outer scope.

UPDATE2: from @viery365 comment you can use this as second argument to forEach and it will make context for the function:

this.addNewObjects = function(arr) {     arr.forEach(function(obj) {         this.addObject(new Obj(obj.prop1, obj.prop2));     }, this); } 

You can read this on MDN forEach page

like image 167
jcubic Avatar answered Sep 28 '22 01:09

jcubic


const array1 = [   {name : "john", age: 20}, {name : "sarah", age: 70}   ];  array1.forEach(element => this.print(element));  print = (data) => {   console.log(data.name); } // expected output: "john" // expected output: "sarah"

There is better way to do this

array.forEach(obj => this.functionName(params));
like image 33
david reachio Avatar answered Sep 28 '22 01:09

david reachio