What is the use of the JavaScript 'bind' method?

后端 未结 19 2390
自闭症患者
自闭症患者 2020-11-21 06:24

What is the use of bind() in JavaScript?

19条回答
  •  执笔经年
    2020-11-21 06:40

    Bind Method

    A bind implementation might look something like so:

    Function.prototype.bind = function () {
      const self = this;
      const args = [...arguments];
      const context = args.shift();
    
      return function () {
        return self.apply(context, args.concat([...arguments]));
      };
    };
    

    The bind function can take any number of arguments and return a new function.

    The new function will call the original function using the JS Function.prototype.apply method.
    The apply method will use the first argument passed to the target function as its context (this), and the second array argument of the apply method will be a combination of the rest of the arguments from the target function, concat with the arguments used to call the return function (in that order).

    An example can look something like so:

    function Fruit(emoji) {
      this.emoji = emoji;
    }
    
    Fruit.prototype.show = function () {
      console.log(this.emoji);
    };
    
    const apple = new Fruit('

提交回复
热议问题