1.call方法的实现
Function.prototype.hycall = function (thisArg, ...nums) {
// 1.获取所要执行的函数
let fn = this
// 2.绑定this
// 边界判断,判断绑定对象是否为空
// Object()方法可以根据参数的值的类型返回相应的基本包装类型的实例
thisArg=(thisArg!==undefined&& thisArg!==null)?Object(thisArg):window
thisArg.fn = fn
// 3.执行函数
let result=thisArg.fn(...nums)
// 4.返回函数的结果
return result
}
function sum(nums1, nums2) {
console.log(this)
return nums1+nums2
}
let obj = { name: 'why' }
// console.log(sum.call(this,1,2))
console.log(sum.hycall(obj,1,2))
2.apply方法的实现
// 实现apply方法
// 1.将方法绑定在Function 的原型对象上
Function.prototype.hyapply=function (thisArg, nums){
// 1.获取函数
let fn = this
// 2.处理绑定对象
thisArg = (thisArg!==undefined&& thisArg!==null) ? Object(thisArg) : window
// 3.执行函数 处理参数,参数为空时赋值为[]
nums = nums || []
thisArg.fn = fn
console.log(thisArg)
let result = thisArg.fn(...nums)
delete thisArg.fn
// 返回函数结果
return result
}
let obj = { name: 'why' }
function sum(num1, num2) {
return num1+num2
}
console.log(sum.hyapply(obj,[1,2]))
3.bind方法的实现
// 实现bind方法
Function.prototype.hybind = function (thisArg, ...argus) {
// 1.获取函数
let fn = this
// 2.获取绑定对象
thisArg = (thisArg !== undefined && thisArg !== null) ? Object(thisArg) : window
function proxyFn(...proxyArgus) {
thisArg.fn = fn
let arg = [...argus, ...proxyArgus]
let result=thisArg.fn(...arg)
delete thisArg.fn
return result
}
// 返回新创建的函数
return proxyFn
}
function sum(...argus) {
let val= argus.reduce((pre, value) => {
return pre + value
})
return val
}
let obj = { name:'why'}
let fn=sum.hybind(obj, 1)
console.log(fn(2,3,4))
总结
这是对js中call、apply和bind方法的简单实现,并没有考虑很多边界条件,如如果绑定对象中已经有fn函数名的处理(可以用Symbol类型:symbol表示唯一的值)等等。欢迎大家一起学习讨论