Setting 'this' in Array.from's Map Function
You'll learn how to control the this context inside Array.from's optional mapping function by passing a third argument.
The Core Idea
Remember how Array.from accepts a second argument—a mapping function that transforms each element? Well, there's an optional third argument that lets you specify what this refers to inside that mapping function.
This is useful when your mapping logic needs access to an object's properties or methods, and you want to bind that object as the context.
The Syntax
Array.from(arrayLike, mappingFunction, thisArg)
The thisArg becomes the value of this inside mappingFunction.
Why This Matters
Without the third argument, this inside the mapping function would be undefined (in strict mode) or the global object. By providing thisArg, you can inject any object you want as the context.
Example in Action
const multiplier = {
factor: 10,
multiply(num) {
return num * this.factor;
}
};
const result = Array.from(
[1, 2, 3],
function(num) {
return this.multiply(num);
},
multiplier // Sets 'this' to the multiplier object
);
console.log(result); // [10, 20, 30]
Here, the third argument (multiplier) makes this refer to that object inside the mapping function, allowing access to this.multiply().
Key Takeaway: Use the third argument of Array.from to explicitly set the this context for the mapping function, giving you access to object methods and properties during transformation.