JS手寫apply、call、bind方法

一、js手寫call:隱式綁定改變this
Function.prototype.customCall = function (thisArg, ...args) {
    // 1、獲取被調(diào)用的函數(shù)
    const fn = this; // 這里的this指向sum

    // 2、綁定this,將thisArg轉(zhuǎn)成對象類型(防止傳入非對象類型)
    thisArg = thisArg ? Object(thisArg) : window;
    thisArg.fn = fn;

    // 3、執(zhí)行函數(shù)
    const result = thisArg.fn(...args);
    delete thisArg.fn;

    // 4、返回執(zhí)行結(jié)果
    return result;
};

function sum (num1, num2) {
    console.log('sum函數(shù)', this, num1, num2, num1 + num2); // sum函數(shù) String{'abc', fn: ?} 10 20 30
    return num1 + num2;
}

sum.customCall('abc', 10, 20);
二、js手寫apply:隱式綁定改變this
Function.prototype.customapply = function (thisArg, args) {
    // 1、獲取被執(zhí)行的函數(shù)
    const fn = this; // 這里的this指向sum函數(shù)

    // 2、綁定this
    thisArg = thisArg ? Object(thisArg) : thisArg; // 處理thisArg為Number/null/undefined的情況
    thisArg.fn = fn;

    // 執(zhí)行函數(shù)
    const result = args ? thisArg.fn(...args) : thisArg.fn(); // args可能為undefined
    delete thisArg.fn;

    // 返回執(zhí)行結(jié)果
    return result;
};

function sum(num1, num2) {
    console.log('sum被調(diào)用', this, num1, num2, num1 + num2); // sum被調(diào)用 String{'abc'} 10 20
    return num1 + num2;
}

function sum1(num) {
    console.log('sum1被調(diào)用', this, num); // sum1被調(diào)用 String{'abc', fn: ?} 10
    return num;
}

function sum2() {
    console.log('sum2被執(zhí)行');
}

sum.customapply('abc', [10, 20]); // 隱式調(diào)用
sum1.customapply('abc', [10]);
sum2.customapply('abc');
三、js手寫bind:隱式綁定改變this
Function.prototype.custombind = function (thisArg, ...args) {
    // 1、獲取被調(diào)用的函數(shù)
    const fn = this;

    // 2、綁定this
    thisArg = thisArg ? Object(thisArg) : window;
    const retFunc = function (...extraArgs) {
        thisArg.fn = fn;
        const result = thisArg.fn(...args, ...extraArgs); // 對兩次傳入的參數(shù)進(jìn)行合并
        delete thisArg.fn;
        return result;
     };

    // 3、直接返回方法,且這個(gè)方法綁定了執(zhí)行參數(shù)
    return retFunc;
};

function sum(num1, num2) {
    console.log('sum被調(diào)用了', this, num1, num2, num1 + num2);
    return num1 + num2;
}

sum.custombind('abc', 10)(20);

另一種手寫bind

Function.prototype.customBind = function() {
    // 獲取要被執(zhí)行的函數(shù)
    const fn = this;

    // 獲取this
    let thisArg = Array.prototype.shift.call(arguments);
    thisArg = thisArg ? Object(thisArg) : window; // 必須,要保證thisArg是個(gè)Object

    // 獲取參數(shù)
    const args = Array.prototype.slice.call(arguments);

    return function() {
      const extraArgs = Array.prototype.slice.call(arguments);
      // 綁定this
      thisArg.fn = fn;
      thisArg.fn(...args, ...extraArgs);
    };
}

function sum (num1, num2) {
    const result = num1 + num2;
    console.log('sum被調(diào)用', this, num1, num2, result);
    return result;
}

sum.customBind('abc', 10)(20); // sum被調(diào)用 String{'abc', fn: ?} 10 20 30
四、認(rèn)識arguments:傳遞給函數(shù)的參數(shù)的類數(shù)組(array-like)對象

類數(shù)組對象:長的像一個(gè)數(shù)組,實(shí)際上是一個(gè)對象
1、擁有數(shù)組的一些特性,例如length、或可以通過index索引來訪問
2、沒有數(shù)組的一些方法,例如forEach、map等

// 認(rèn)識arguments
 function sum(num1, num2, num3) {
    // 打印arguments
    console.log(arguments); // Arguments(3)[1, 2, 3, callee: ?, Symbol(Symbol.iterator): ?]

    // 常見的對arguments的操作有三個(gè):
    // 1、獲取參數(shù)長度
    console.log(arguments.length); // 3

    // 2、根據(jù)索引值獲取某一個(gè)參數(shù)
    console.log(arguments[0]); // 1

    // 3、callee獲取當(dāng)前arguments所在的函數(shù)
    console.log(arguments.callee); // function sum(num1, num2, num3) {}
}
sum(1, 2, 3);
// 類數(shù)組轉(zhuǎn)數(shù)組
function sum(num1, num2, num3) {
    // 方法一:自己遍歷
    // const newArr = [];
    // for (let i = 0; i < arguments.length; i++) {
    //   newArr.push(arguments[i] * 2);
    // }
    // return newArr;

    // 方法二:slice(借助slice內(nèi)部的遍歷)
    // const newArr = Array.prototype.slice.call(arguments);
    // 或
    // const newArr = [].slice.call(arguments);
    // return newArr;

    // 方法三:ES6的from方法
    // const arr = Array.from(arguments);
    // return arr.map(v => v * 2);

    // 方法四:展開運(yùn)算符
    const arr = [...arguments];
    return arr.map(v => v * 2);
}
sum(1, 2, 3);
// 箭頭函數(shù)中沒有arguments,會(huì)去上層作用域找
const hello = () => {
    // console.log(arguments); // arguments is not defined
};

const hi = function () {
    const fn = () => {
        console.log(arguments); // Arguments[123, callee: ?, Symbol(Symbol.iterator): ?]
    };
    return fn();
};

hello();
hi(123);
五、bind的一些面試題

???????bind()方法主要就是將函數(shù)綁定到某個(gè)對象,bind()會(huì)創(chuàng)建一個(gè)函數(shù),函數(shù)體內(nèi)的this對象的值會(huì)被綁定到傳入bind()中的第一個(gè)參數(shù)的值,例如:f.bind(obj),實(shí)際上可以理解為obj.f(),這時(shí)f函數(shù)體內(nèi)的this自然指向的是obj;

  var a = {
    b: function() {
      var func = function() {
        console.log(this.c);
      }
      func();
    },
    c: 'hello'
  }
  a.b(); // undefined 這里的this指向的是全局作用域
  console.log(a.c); // hello
  var a = {
    b: function() {
      var _this = this; // 通過賦值的方式將this賦值給that
      var func = function() {
        console.log(_this.c);
      }
      func();
    },
    c: 'hello'
  }
  a.b(); // hello
  console.log(a.c); // hello
// 使用bind方法一
  var a = {
    b: function() {
      var func = function() {
        console.log(this.c);
      }.bind(this);
      func();
    },
    c: 'hello'
  }
  a.b(); // hello
  console.log(a.c); // hello

// 使用bind方法二
  var a = {
    b: function() {
      var func = function() {
        console.log(this.c);
      }
      func.bind(this)();
    },
    c: 'hello'
  }
  a.b(); // hello
  console.log(a.c); // hello
// 分析:這里的bind方法會(huì)把它的第一個(gè)實(shí)參綁定給f函數(shù)體內(nèi)的this,所以里的this即指向{x:1}對象;
// 從第二個(gè)參數(shù)起,會(huì)依次傳遞給原始函數(shù),這里的第二個(gè)參數(shù)2即是f函數(shù)的y參數(shù);
// 最后調(diào)用m(3)的時(shí)候,這里的3便是最后一個(gè)參數(shù)z了,所以執(zhí)行結(jié)果為1+2+3=6
// 分步處理參數(shù)的過程其實(shí)是一個(gè)典型的函數(shù)柯里化的過程(Curry)
  function f(y,z){
    return this.x+y+z;
  }
  var m = f.bind({x:1},2);
  console.log(m(3)); // 6
// 分析:直接調(diào)用a的話,this指向的是global或window對象,所以會(huì)報(bào)錯(cuò);
// 通過bind或者call方式綁定this至document對象即可正常調(diào)用
  var a = document.write;
  a('hello'); // error
  a.bind(document)('hello'); // hello
  a.call(document,'hello'); // hello
// 實(shí)現(xiàn)預(yù)定義參數(shù)
// 分析:Array.prototype.slice.call(arguments)是用來將參數(shù)由類數(shù)組轉(zhuǎn)換為真正的數(shù)組;
  function list() {
    return Array.prototype.slice.call(arguments);
  }
  var list1 = list(1, 2, 3); // [1,2,3]
// 第一個(gè)參數(shù)undefined表示this的指向,第二個(gè)參數(shù)10即表示list中真正的第一個(gè)參數(shù),依次類推
  var a = list.bind(undefined, 10);
  var list2 = a(); // [10]
  var list3 = a(1, 2, 3); // [10,1,2,3]
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,578評論 6 544
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 99,701評論 3 429
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,691評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,974評論 1 318
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 72,694評論 6 413
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 56,026評論 1 329
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 44,015評論 3 450
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 43,193評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,719評論 1 336
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 41,442評論 3 360
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 43,668評論 1 374
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,151評論 5 365
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,846評論 3 351
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,255評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,592評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 52,394評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 48,635評論 2 380

推薦閱讀更多精彩內(nèi)容

  • 第2章 基本語法 2.1 概述 基本句法和變量 語句 JavaScript程序的執(zhí)行單位為行(line),也就是一...
    悟名先生閱讀 4,193評論 0 13
  • 函數(shù)和對象 1、函數(shù) 1.1 函數(shù)概述 函數(shù)對于任何一門語言來說都是核心的概念。通過函數(shù)可以封裝任意多條語句,而且...
    道無虛閱讀 4,614評論 0 5
  • 函數(shù)只定義一次,但可能被執(zhí)行或調(diào)用任意次。JS函數(shù)是參數(shù)化的,函數(shù)的定義會(huì)包括一個(gè)稱為形參的標(biāo)識符列表,這些參數(shù)在...
    PySong閱讀 862評論 0 0
  • 依舊低飛的蜻蜓 在溝渠積水里映出自己 它們來不及逃跑或者飛高 陽光就散開了 空氣里被一掃而空 干凈的一覽無余,大概...
    鹿原先生和蓬蒿閱讀 1,009評論 6 30
  • 老師泄題,學(xué)校亂收費(fèi),刻意而為的打手,一切看分?jǐn)?shù)的社會(huì)大勢,甚至那些利用琳的有錢人,他們被遣返回國以后,也可以過著...
    張十九L閱讀 299評論 0 0