前言
call/apply的核心理念就是借用方法,
這話乍一聽上去,感覺有點云里霧里,講一個生活中的實體來描述一下:
老鄧和老王是鄰居,老鄧家有火鍋,老王家有燒烤架,老王家很少吃火鍋,但突然有一天想吃火鍋,他就可以去老鄧家借用火鍋,這樣老王家不僅吃上了火鍋,還沒花買鍋的錢,同樣如果有一天老鄧家想吃燒烤,便可以去老王家借燒烤架,
call/apply做的便是類似的事,A物件上實作了一個方法,B物件由于一些需求,也需要呼叫同樣的方法,最好的方法肯定是B直接去呼叫A物件的方法,自身無需擴展,
基本介紹
語法:
fn.call(thisArg, arg1, arg2,...)
fn.apply(thisArg, [arg1, arg2,...])
引數
thisArg(可選):fn函式的this指向thisArgthisArg傳入null,undefined:非嚴格模式下:fn函式this->window;嚴格模式:this->undefined- 值為原始值(數字,字串,布爾)時,this指向包裝類
arg1,arg2(可選): 傳給fn的引數- apply傳遞的第二個引數為陣列
作用
改變this指向
常見用法
- 判斷資料型別:
typeof方法只回傳七種值:string、number、boolean、undefined、object、function、symbol,所以使用typeof是無法區分array和普通物件的,
arr = []
typeof(arr) // "object"
obj = {}
typeof(obj) // "object"
Object.prototype.toString方法可以判斷所有的型別,但Array、String等都重寫了該方法,因此就需要借助call/apply來實作
Object.prototype.toString.call(arr) // "[object Array]"
Object.prototype.toString.call(obj) // "[object Object]"
- 類陣列呼叫陣列的方法
ES6未發布之前,沒有Array.from方法可以將類陣列轉為陣列,采用Array.prototype.slice.call(arguments)或[].slice.call(arguments)將類陣列轉化為陣列,
當然別的陣列方法也可以類似呼叫,例如push方法:
var arraylike = {
0: 1,
length: 1
}
Array.prototype.push.call(arrlike, 1) // {0: 1, 1: 2, length: 2}
apply求陣列的最大值與最小值
JavaScript中沒有給陣列提供類似max和min函式,只提供了Math.max/min,用于求多個數的最值,所以可以借助apply方法,直接傳遞陣列給Math.max/min
const arr = [1,10,11,33,4,52,17]
Math.max.apply(Math, arr)
Math.min.apply(Math, arr)
手撕call
初步模擬
首先看一個簡單例子,分析一下call函式執行程序:
var obj = {
value: 1
}
function fun() {
console.log(this.value)
}
fun.call(obj) // 1
可見call函式呼叫大致執行了兩部:
call改變了this指向,this->objfun函式執行
那該如何模擬上面的效果那?如果在obj上定義函式fun,之后obj.fun執行是不是就達成了上述的效果,
所以call的模擬步驟大約是:
- 將函式
fn設為thisArg的物件的方法 - 執行
thisArg.fn - 洗掉該函式
Function.prototype.myCall = function (thisArg) {
// this為呼叫myCall的函式
thisArg.func = this;
thisArg.func();
delete(thisArg.func);
}
完善
上面實作了call的最初版代碼,還有幾個地方有待解決:
- 未傳入
thisArg引數:當未傳入thisArg或傳入null時,函式的this->window
thisArg = thisArg || window
- 傳入
arg1,arg2等引數:ES6可以通過rest引數來實作,ES6以前可以通過arguments來實作
// ES5
const args = []
for (let i = 1; i<arguments.length; i++) {
args.push('argumens['+ i + ']')
}
eval('thisArg.func(' + args +')')
eval()函式計算JavaScript字串,并把它作為腳本代碼來執行,array在與字串相加時,會呼叫array.toString方法([1,2,3].toString() // "1,2,3"),
- 函式可以擁有回傳值
舉個例子:
const obj = {
value: 1
}
function func(name, age) {
return {
name,
age,
value: this.value
}
}
func.call(obj, 'zcxiaobao', 24)
// {
// age: 24,
// name: "zcxiaobao",
// value: 1,
// }
不過很好解決,因此只需將eval執行之后的結果回傳即可,
接著我們來看一下完整版的代碼:
Function.prototype.myCall = function (thisArg) {
thisArg = thisArg || window;
thisArg.func = this;
const args = []
for (let i = 1; i<arguments.length; i++) {
args.push('arguments['+ i + ']')
}
const result = eval('thisArg.func(' + args +')')
delete thisArg.func;
return result;
}
如果使用ES6語法進行模擬代碼會簡單很多
Function.prototype.myCall = function (thisArg, ...args) {
thisArg = thisArg || window;
thisArg.func = this;
args = args || []
const result = thisArg.func(..args)
delete thisArg.func;
return result;
}
手撕apply
apply的代碼實作與call類似,這里直接給代碼,
Function.prototype.myApply = function (thisArg, arr) {
thisArg = thisArg || window;
thisArg.func = this;
const args = []
for (let i = 0; i<arr.length; i++) {
args.push('arr['+ i + ']')
}
const result = eval('thisArg.func(' + args +')')
delete thisArg.func;
return result;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/304958.html
標籤:其他
上一篇:前端之變(三):變革與突破
