I am sorry if this is a really stupid question. I have searched about it and couldn't find a clear answer. There is a factory function in a tutorial on the web like the one below. I have mostly understood how "This
" works in other places but I can't quite wrap my head around how "This
" helps us here. The code still works even when I remove "This
". I also don't understand why removing "return color;
" breaks "color.rgb()
".
function makeColor(r, g, b) {
const color = {};
color.r = r;
color.g = g;
color.b = b;
color.rgb = function () {
//const { r, g, b } = this;
return `rgb(${r}, ${g}, ${b})`;
};
return color;
}
const newColor = makeColor(50, 100, 150);
newColor.rgb();
console.log(newColor); // {r: 50, g: 100, b: 150, rgb: ƒ}
console.log(newColor.rgb()); //rgb(50, 100, 150)