什么是call竟坛、apply、bind涎跨?
共同點:調用一個function,并將function中的this指向指定的對象六敬。
不同點:1驾荣、apply的參數(shù)中普泡,除指定對象外,其余參數(shù)組合為一個數(shù)組作為第二個參數(shù)撼班;
????2垒酬、call、apply返回函數(shù)執(zhí)行完的結果勘究,bind是返回一個function。
簡單的例子:
var x = 1;
function add (y) {
console.log(this.x + y)
}
add(2) // 5口糕, 非嚴格模式下,this 指向 window十办,所以 this.x 為 1
var obj = { x: 3 }
add.call(obj, 2) // 5超棺, this 指向 obj,所以this.x 即obj.x棠绘,2 作為參數(shù) y 傳遞
add.apply(obj, [2]) // 5, this 指向 obj弄唧,所以this.x 即obj.x,注意第二個參數(shù)為數(shù)組
add.bind(obj, 2)() // 5侯养, 返回 this 指向 obj 的函數(shù)澄干,this.x 即obj.x,2 作為參數(shù) y 傳遞
實現(xiàn)call麸俘、apply、bind的重點就是將 this 指向指定的對象从媚。看下面代碼:
var obj = {
a: 'text',
showA: function () {
console.log(this.a)
}
}
obj.showA() // text, this 指向 obj
所以喷众,利用 obj.fn() 中 this 指向 obj 的特性就可以實現(xiàn)call、apply到千、bind!0蛳ⅰ了赵!
call:
Function.prototype.myCall = function (context, ...argList) {
context._fn = this;
context._fn(...argList)
delete context._fn // 執(zhí)行函數(shù)后刪除該對象屬性
}
apply:
Function.prototype.myApply = function (context, argList) {
context._fn = this;
context._fn(...argList)
delete context._fn
}
bind(返回函數(shù)):
Function.prototype.myBind = function (context, ...argList) {
// 不用call、apply實現(xiàn)
context._fn = this;
return () => {
context._fn(...argList)
delete context._fn
}
// 用 call 實現(xiàn) bind(apply類似)
return () => {
this.call(context, ...argList)
}
}