Using Another Type's Methods
Sometimes an object needs methods from a type it isn't. The classic example: arguments inside a function looks like an array but isn't — so it lacks array methods.
function logArgs() {
// arguments has no .join() — so we borrow it:
const result = Array.prototype.join.call(arguments, ', ');
console.log(result);
}
logArgs(1, 2, 3); // "1, 2, 3"
Modern Alternative: Array.from() or Rest Parameters
// Convert to a real array first
function logArgs(...args) {
console.log(args.join(', ')); // args is already a real array
}
| Method | Behavior |
|---|---|
fn.call(thisArg, a, b) | Calls fn with this = thisArg |
fn.apply(thisArg, [a, b]) | Same but arguments as array |
fn.bind(thisArg) | Returns a new permanently-bound function |
Note
call, apply, and bind all let you control what this refers to inside a function — they just differ in syntax.