This keyword not accessible using forEach loop in script include?

aman_sharma_07
Tera Guru

Hi folks!

 

I was playing around the for loops in the script includes as trying to develop some reusable piece of code for custom requirements.

 

I've noticed some unusual behavior of using forEach array loop over normal for Loop.

The script include's global variable "this" was not accessible there.

 

To validate the same, following is the background script code

 

var array = [32,43,544,56,32,54,66,33,222,4656,454,5432,53,5,21,475];
gs.info('printUsingForLoop : ');
new testPrint().printUsingFor(array);
gs.info('printUsingForEachLoop : ');
new testPrint().printUsingForEach(array);

 

And the following is the Script Include I created.

 

var testPrint = Class.create();
testPrint.prototype = {
    initialize: function() {},
    printUsingFor: function(arr) {
        for (i = 0; i < arr.length; i++)
			this.printElement(arr[i]);
    },

    printUsingForEach: function(arr) {
		arr.forEach(function(ele){
			this.printElement(ele);
		});
    },

    printElement: function(e) {
        gs.print(e);
    },
    type: 'testPrint'
};

 

This was the result: 

 

*** Script: printUsingForLoop : 
*** Script: 32
*** Script: 43
*** Script: 544
*** Script: 56
*** Script: 32
*** Script: 54
*** Script: 66
*** Script: 33
*** Script: 222
*** Script: 4656
*** Script: 454
*** Script: 5432
*** Script: 53
*** Script: 5
*** Script: 21
*** Script: 475
*** Script: printUsingForEachLoop : 

 

 

Let me know if it is a known bug or if there's something I'm missing..

 

Thanks in advance!

1 ACCEPTED SOLUTION

Chaitanya ILCR
Kilo Patron

Hi @aman_sharma_07 ,

Try this out

var testPrint = Class.create();
testPrint.prototype = {
    initialize: function() {},
    printUsingFor: function(arr) {
        for (i = 0; i < arr.length; i++)
			this.printElement(arr[i]);
    },

    printUsingForEach: function(arr) {
		arr.forEach(function(ele){
			this.printElement(ele);
		},this);
    },

    printElement: function(e) {
        gs.print(e);
    },
    type: 'testPrint'
};

Hope this article will help you 
https://pullthecode.com/blog/understanding-the-this-context-in-javascripts-foreach-method

Regards,
Chaitanya

View solution in original post

3 REPLIES 3

Vinuthna Ammana
Mega Guru

Chaitanya ILCR
Kilo Patron

Hi @aman_sharma_07 ,

Try this out

var testPrint = Class.create();
testPrint.prototype = {
    initialize: function() {},
    printUsingFor: function(arr) {
        for (i = 0; i < arr.length; i++)
			this.printElement(arr[i]);
    },

    printUsingForEach: function(arr) {
		arr.forEach(function(ele){
			this.printElement(ele);
		},this);
    },

    printElement: function(e) {
        gs.print(e);
    },
    type: 'testPrint'
};

Hope this article will help you 
https://pullthecode.com/blog/understanding-the-this-context-in-javascripts-foreach-method

Regards,
Chaitanya

That works @Chaitanya ILCR !

 

Thanks for your help!