Exercise 8: Bind Function (custom implementation)
Problem Statement
Create a function `bind(fn, context, ...args)` that binds function with context and partial args.
Sample Output:
const obj = {x: 10};
const bound = bind(function(y) { return this.x + y; }, obj, 5);
bound(3) => 18Solution
const bind = (fn, context, ...boundArgs) => {
return (...args) => fn.apply(context, [...boundArgs, ...args]);
};Explanation
Overall Goal:
- Function ko context aur args ke saath bind karna.
Line 1: Function header
const bind = (fn, context, ...boundArgs) => {
Line 2: Return bound function
return (...args) => fn.apply(context, [...boundArgs, ...args]);
Real world:
- Method binding: context preservation.
- Event handlers: this binding.