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

后端 未结 4 1904
没有蜡笔的小新
没有蜡笔的小新 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条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-24 16:11

    .apply() is a method on function objects. Like so:

    console.log(Math.max.apply(null, [1, 2, 3])); // 3

    .apply() accepts two arguments, the context (what would become this inside of the target function) and an iterable of arguments (usually an array, but the arguments array like also works).


    .bind() is a method on function objects. Like so:

    const x = {
      foo: function() {
        console.log(this.x);
      },
      x: 42
    }
    
    var myFoo = x.foo.bind({x: 5});
    
    x.foo(); // 42
    myFoo(); // 5

    .bind() takes a context (what would become this), and optionally, additional arguments, and returns a new function, with the context bound, and the additional arguments locked


    Since .apply() is a function in on itself, it can be bound with .bind(), like so:

    Function.prototype.apply.bind(fn, null);
    

    Meaning that the this of .apply() would be fn and the first argument to .apply() would be null. Meaning that it would look like this:

    fn.apply(null, args)
    

    Which would spread the parameters from an array.

提交回复
热议问题