call()/apply()方法的主要功能: 調(diào)用函數(shù),指定函數(shù)中的this為第一個參數(shù)的值
bind() : 返回一個新的函數(shù),新函數(shù)內(nèi)部會調(diào)用原來的函數(shù),且this為第一參數(shù)的值
自定義方法代碼如下:
<script>
//自定義call方法
Function.prototype.call = function (obj,...rest) {
//判斷第一個參數(shù)是否是null或者undefined,如果是使其指向window
if(obj === null || obj === undefined) return this(...rest)
//給指定的對象添加一個臨時(shí)方法,方法的函數(shù)就是要改變指向的函數(shù)
obj.temp = this
//執(zhí)行方法,改變原來函數(shù)體中this的指向
const result = obj.temp(...rest)
//刪除添加的臨時(shí)方法
delete obj.temp
//返回執(zhí)行結(jié)果
return result
}
//call與apply的沒有什么大的差異,只有接受實(shí)參的形參數(shù)據(jù)類型不同,call接受的數(shù)值數(shù)據(jù),而apply接受的數(shù)組數(shù)據(jù).
Function.prototype.apply = function (obj,args) {
if(obj === null || obj === undefined) return this(...args)
obj.temp = this
const result = obj.temp(...args)
delete obj.temp
return result
}
//bind方法返回一個新函數(shù),在新函數(shù)的內(nèi)部利用call方法,調(diào)用了原來的函數(shù),改變了this的指向.
Function.prototype.bind = function (obj,...args) {
const that = this
return function (...args2) {
return that.call (obj,...args,...args2)
}
}
</script>
?```