Skip to content Skip to sidebar Skip to footer

Using `this` In A Foreach()

(Disclaimer: I'm in the process of learning JavaScript) I have an object constructor like so: var Palette = function() { this.colors = ['red', 'green', 'blue']; this.getCol

Solution 1:

Pass this as the second parameter to forEach

arr.forEach(callback, thisArg);

Per MDN Documentation:

thisArg: Optional. Value to use as this when executing callback.

I've updated your fiddle to show it's usage, but the gist is change this call:

this.colors.forEach(function(a) {
    this.colors.forEach(function(b) {
        if(a !== b) {
            combos.push([a, b]);
        }
    });
});

To this:

this.colors.forEach(function(a) {
    this.colors.forEach(function(b) {
        if(a !== b) {
            combos.push([a, b]);
        }
    });
}, this); // <- pass this as second arg

Also of note is that many other Array.prototype methods that accept a callback also support this idiom, including:

  • forEach
  • map
  • every
  • some
  • filter

However, if you just need to specify what this is bound to when calling a function, and that function is not set as a property on the object, then probably the most idiomatic way would be with Function.prototype.call() or Function.prototype.apply().

And if ES6 is available to you, then an arrow function would be even better, as it inherits this from the calling context:

this.colors.forEach(a => {
    this.colors.forEach(b => {
        if(a !== b) {
            combos.push([a, b]);
        }
    });
});

Post a Comment for "Using `this` In A Foreach()"