(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.getColorCombinations = function() {
var combos = [];
this.colors.forEach(function(a) {
this.colors.forEach(function(b) {
if(a !== b) {
combos.push([a, b]);
}
});
});
return combos;
};
}
var p = new Palette();
alert(JSON.stringify(p.getColorCombinations()));
With the expected output:
[["red","green"],["red","blue"],["green","red"],["green","blue"],["blue","red"],["blue","green"]]
After some research I realize now that this doesn't work because in the inner anonymous functions, "this" points to the global object and not the Palette instance anymore.
My question is, what is the "JavaScript way" to deal with this? I see similar problems solved with Apply, Bind, Call or simply assigning this
to a variable, but so far I've not found any examples of which way is consistently best practice for referencing this
in inner anonymous functions.
here is the JsFiddle. (I modified it to output to a div for easier text copying)