JavaScript鄙視題 - 重寫bind

簡介

上一篇, 咱們介紹了JavaScript鄙視題 - 重寫forEach, 咱們繼續介紹如何手寫一個bind方法.javascript

方法介紹

bind()方法建立一個新的函數,在bind()被調用時,這個新函數的this被bind的第一個參數指定,其他的參數將做爲新函數的參數供調用時使用.java

舉個例子:函數

const say = function(message) {
      return `${this.name} ${message}`
    };
    const jack = {name: 'jack'};
    const joe = {name: 'joe'};

    const jackSay = say.bind(jack);
    const joeSay = say.bind(joe);

    console.log(jackSay(', I am jack'));
    console.log(joeSay(', I am joe'));
    
    // output
    // jack, I am jack
    // joe, I am joe
複製代碼

通俗一點的講, 就是改變執行函數this的指向.post

重寫bind方法.

Function.prototype.bind = function(obj, ...rest){
  const fn = this;
  return function(...args){
    return fn.call(obj, rest.concat(args));
  }
};
複製代碼

看起來是否很是的簡單.ui

相關文章
相關標籤/搜索