apply
Function.prototype.myApply = function (thisArg, ArgArray) {
if (typeof thisArg == 'undefined' || typeof thisArg == null) {
thisArg = window
}
let fnSymbol = Symbol()
thisArg[fnSymbol] = this
let ret = thisArg[fnSymbol](...ArgArray)
delete thisArg[fnSymbol]
return ret
}
function say(age) {
console.log(`我的名字是${this.name},年龄${age}啦`)
}
say.myApply({ name: 'zhq' }, [18])
call
Function.prototype.myCall = function (thisArg, ...ArgArray) {
if (typeof thisArg === 'undefined' || typeof thisArg === null) {
thisArg = window
}
let fnSymbol = Symbol()
thisArg[fnSymbol] = this
let ret = thisArg[fnSymbol](...ArgArray)
delete thisArg[fnSymbol]
return ret
}
function say(age) {
console.log(`我的名字是${this.name},年龄${age}啦`)
}
say.myApply({ name: 'zhq' }, [18])
bind
Function.prototype.myBind = function (thisArg, ...ArgArray) {
let thatFunc = this
return function () {
thatFunc.apply(thisArg, ArgArray)
}
}
上面仅为实现,没有兼容性
Polyfill写法
if (!Function.prototype.bind){
;(function(){
let slice = Array.prototype.slice;
let thatArg = arguments[0];
let args = slice.call(arguments, 1);
Function.prototype.bind = function (thisArg, ...ArgArray) {
let thatFunc = this
return function () {
let funcArgs = args.concat(slice.call(arguments))
thatFunc.apply(thatArg, funcArgs)
}
}
})()
}