隐式绑定和显式绑定实现一个apply
apply作用是改变this的指向。在js中有两种方式改变this的指向。一种是显式的也就是apply、call和bind;另外一种就是隐式的。
因此手动实现apply也就至少有两种方法。
利用隐式绑定。
Function.prototype.myapply1 = function(target, args){
if(typeof args === 'undefined' || args === null) {
args = []
}
if(typeof target === 'undefined' || target === null) {
target = window
}
target = new Object(target)
const targetkey = 'targetkey'
target[targetkey] = this
const result = target[targetkey](...args) // 借助隐式绑定实现this执行改写
delete target[targetkey]
return result
}
利用显式绑定,借助call或者bind
// 利用显示绑定 借助call
Function.prototype.myapply2 = function(target, args){
if(typeof args === 'undefined' || args === null) {
args = []
}
if(typeof target === 'undefined' || target === null) {
target = window
}
const result = this.call(target, ...args)
return result
}
我站在山顶看风景!下面是我的家乡!


浙公网安备 33010602011771号