How does function.apply.bind work in the following code?

后端 未结 4 1905
没有蜡笔的小新
没有蜡笔的小新 2020-12-24 15:58

So I get that an array of [200,599] is returned from the promise and the callback function inside spread is being passed into Function.apply.bind, but now I\'m lost. How is

4条回答
  •  旧时难觅i
    2020-12-24 16:17

    The reason it works is the "destructuring" nature of apply (if given an array of values, they would be provided spreaded to the function you use apply on).

    Now back to your code when calling bind on apply, the value returned is a function which returns the same function provided to bind, the only thing different is when executed it would be called using apply (with an array as thisArg in your case), but it isn't going to be executed until you call it. In your case when the promise has resolved, the function provided tothen woule be executed with an array of arguments provided by Promise resolution.

    function spread(fn){
       let boundedFn = fn.bind(fn)
    
       return function(arg){
          return boundedFn.apply(null,arg)
       }
    }
       
    spread((x, y, c) => console.log(x, y, c))([1,2,3])
    
    // or
    
    Promise.resolve([6, 5]).then(spread((a, b) => console.log(a, b)))

    The reason bind is provided (in your code) with null as second param is to prevent the array provided by the caller from being given to apply as its first param, which reserved for this.

提交回复
热议问题