Function Wrappers

A decorator is a function that takes another function and changes its behavior (e.g., adds caching or logging).

call and apply

To correctly pass the this context into the wrapped function, the call and apply methods are used.

function wrapper(f) {
  return function() {
    console.log("Log: Call starting");
    return f.apply(this, arguments); // Passing the context and all arguments
  };
}
  • call: arguments are passed comma-separated f.call(ctx, arg1, arg2).
  • apply: arguments are passed as an array f.apply(ctx, [arg1, arg2]).
Tip

The bind method returns a copy of a function with a hard-bound context, which is useful for callbacks.