手写apply,bind,call函数
程序员文章站
2022-07-14 14:16:03
...
Function.prototype.myCall = function(content){
if(typeof this !== 'function'){
throw new Error('err')
}
const obj = content || window
obj.fn = this
const args = Array.prototype.slice.myApply(arguments,[1])
const res = obj.fn(...args)
delete obj.fn
return res
}
Function.prototype.myApply = function(content){
if(typeof this !== 'function'){
throw new Error('err')
}
const obj = content || window
obj.fn = this
const args = arguments[1] || []
const res = obj.fn(...args)
delete obj.fn
return res
}
Function.prototype.myBind = function(content){
if(typeof this !== 'function'){
throw new Error('err')
}
//获取参数
const args = Array.prototype.slice.myCall(arguments,1)
//该this指的是调用bind函数的那个函数对象
const self = this
//设置一个空函数用来拷贝这个函数的原型
let fNop = function(){}
let fn = function(){
//这个函数里面的this指的是经历了fn1 = fn.bind()
//之后生成的新的函数fn1被谁调用
//因为new的this优先级是高于bind的,所以如果当fn1通过newfn = new fn1()
//实例化之后,fn1将不会指向bind绑定的那个this而是指向了newfn
//所以我们要做如下处理
let _this = this instanceof self ? this : content
return self.myApply(_this, args.concat(Array.prototype.slice.myApply(arguments)))
}
if(this.prototype){
fNop.prototype = this.prototype
}
fn.prototype = new fNop()
return fn
}