#Pollyfill bind

3 messages · Page 1 of 1 (latest)

umbral willow
#

This is the pollyfill bind implementation. My doubt is regarding the args1. How is it possible to accept args1 in the return function of mybind() ? I'm unable to wrap my head around this concept

let person = {
  firstname: "Kirtesh",
  lastname: "bansal"
}

let printName = function (country) {
  console.log(this.firstname + " " + this.lastname + " from " 
  + country);
}

Function.prototype.mybind = function(object,...args){
  let func = this;
  return function (...args1) {
    return func.apply(object, [...args, ...args1]);
  }
}

let newPrintName = printName.mybind(person, "India");
newPrintName(); ```
bitter snow
#

@umbral willow 👋 It's just the regular rest parameter syntax. Here's a contrived example that might be easier to understand because it's simpler. The outer getGreeter() function is pointless in this example, but hopefully it helps illustrate the point:

function getGreeter() {
    return function (name) {
        return `Hi, ${name}!`;
    };
}

// `getGreeter()` returns a function (with a single parameter) that we assign to `greet`
const greet = getGreeter();

console.log(greet.length); // 1 (the function has 1 parameter)

const greeting = greet("Priya");
console.log(greeting); // "Hi, Priya!"

In this example, the getGreeter() function returns another function with a single parameter, name. This is akin to the ...args1 rest parameter in your example.

This works because JavaScript supports first-class functions, which means functions can be passed around like any other value. This means we can accept them as an argument to a function (sometimes known as a callback function) or return them from a function. In this case, it's a function that returns another function.

Both of these -- a function that accepts another function as an argument, or a function that returns another function -- are sometimes known as a higher-order function.

I typed this up in haste, but let me know if I can explain this any better!

umbral willow