在實現自己的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方法:
新聞熱點
疑難解答
圖片精選