国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > JS > 正文

如何使用50行javaScript代碼實現簡單版的call,apply,bind

2024-05-06 16:54:12
字體:
來源:轉載
供稿:網友

在實現自己的call,apply,bind前,需要復習一下this.

所謂的this其實可以理解成一根指針:

其實 this 的指向,始終堅持一個原理:this 永遠指向最后調用它的那個對象,這就是精髓。最關鍵所在

this的四種指向:

當this所在的函數被普通調用時,指向window,如果當前是嚴格模式,則指向undefined

function test() { console.log(this);};test();指向window 輸出下面的代碼:// Window {speechSynthesis: SpeechSynthesis, caches: CacheStorage, localStorage: Storage, sessionStorage: Storage, webkitStorageInfo: DeprecatedStorageInfo…}
嚴格模式'use strict';function test() { console.log(this);};test();// undefined

當this所在當函數被以obj.fn()形式調用時,指向obj

var obj = { name: 'segmentFault', foo: function() {  console.log(this.name); }}obj.foo();// 'segmentFault'

還可以這么做

function test() { console.log(this.name);}var obj = { name: 'qiutc', foo: test}obj.foo();// 'qiutc'

當call,apply加入后,this的指向被改變了

 function a(a,b,c) {    console.log(this.name);    console.log(a,b,c)  }  const b = {    name: "segmentFault"  }  a.call(b,1,2,3)      //輸出 segmentFault和 1,2,3  function a(a,b,c) {    console.log(this.name);    console.log(a,b,c)  }  a.apply(b,[1,2,3])  //輸出segmentFault和1,2,3

遇到bind后 :

  function a() {    console.log(this.name);  }  const b = {    name: "segmentFault"  }  a.bind(b, 1, 2, 3)

此時控制臺并沒有代碼輸出,因為bind會重新生成并且返回一個函數,這個函數的this指向第一個參數

  function a() {    console.log(this.name);  }  const b = {    name: "segmentFault"  }  const c = a.bind(b, 1, 2, 3)  c()  //此時輸出segmentFault

正式開始自己實現call :

在函數原型上定義自己的myCall方法:

 Function.prototype.myCall = function (context, ...arg) {    const fn = Symbol('臨時屬性')    context[fn] = this    context[fn](...arg)    delete context[fn]  }

四行代碼實現了簡單的call,思路如下:

  • 通過對象屬性的方式調用函數,這個函數里面的this指向這個對象
  • 每次調用新增一個symbol屬性,調用完畢刪除
  • 這個symbol屬性就是調用mycall方法的函數
  • 函數形參中使用...arg是將多個形參都塞到一個數組里,在函數內部使用arg這個變量時,就是包含所有形參的數組
  • 在調用 context[fn](...arg)時候,...arg是為了展開數組,依次傳入參數調用函數

為了簡化,今天都不做類型判斷和錯誤邊際處理,只把原理講清楚。

自己實現apply

在函數原型上定義自己的myApply方法:

//實現自己的myApply  Function.prototype.myApply = function (context, arg) {    const fn = Symbol('臨時屬性')    context[fn] = this    context[fn](...arg)    delete context[fn]  }  const obj2 = {    a: 1  }  test.myApply(obj2, [2, 3, 4])

同理,只是apply傳遞的第二個參數是數組,這里我們只需要在調用時,將參數用...把數組展開即可

自己實現bind:

bind跟apply,call的本質區別,bind不會改變原函數的this指向,只會返回一個新的函數(我們想要的那個this指向),并且不會調用。但是apply和bind會改變原函數的this指向并且直接調用

bind在編寫框架源碼,例如koa等中用得特別多:

 //實現自己的myBind  Function.prototype.myBind = function (context, ...firstarg) {    const that = this    const bindFn = function (...secoundarg) {      return that.myCall(context, ...firstarg, ...secoundarg)    }    bindFn.prototype = Object.create(that.prototype)    return bindFn  }  var fnbind = test.myBind(obj, 2)  fnbind(3)

同理 自己定義好原型上的myBind方法

this劫持 保留最初的調用mybind方法的那個對象

返回一個新的函數 這個新的函數內部this指向已經確定,使用的是我們的mycall方法

學習需要循序漸進,建議根據本文順序去封裝一遍,是比較輕松的,當然bind還需要判斷是否是new調用.

完整版本bind

Function.prototype.myBind = function (objThis, ...params) {  const thisFn = this; // 存儲源函數以及上方的params(函數參數)  // 對返回的函數 secondParams 二次傳參  let fToBind = function (...secondParams) {    console.log('secondParams',secondParams,...secondParams)    const isNew = this instanceof fToBind // this是否是fToBind的實例 也就是返回的fToBind是否通過new調用    const context = isNew ? this : Object(objThis) // new調用就綁定到this上,否則就綁定到傳入的objThis上    return thisFn.call(context, ...params, ...secondParams); // 用call調用源函數綁定this的指向并傳遞參數,返回執行結果  };  fToBind.prototype = Object.create(thisFn.prototype); // 復制源函數的prototype給fToBind  return fToBind; // 返回拷貝的函數};

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。


注:相關教程知識閱讀請移步到JavaScript/Ajax教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 清丰县| 汤原县| 梁山县| 太保市| SHOW| 长武县| 富锦市| 西畴县| 临武县| 遂川县| 正定县| 长垣县| 山东| 双城市| 定结县| 台州市| 贵州省| 江阴市| 弥勒县| 富民县| 大化| 武义县| 长治县| 南和县| 承德县| 丰县| 奎屯市| 洪雅县| 德化县| 寻甸| 德化县| 蓝田县| 锡林郭勒盟| 萨迦县| 根河市| 如东县| 五台县| 南木林县| 定陶县| 高青县| 义乌市|