深入JavaScript Day06 - call、bind的j
2022-01-13 本文已影响0人
望穿秋水小作坊
1、call
// 给所有的函数添加一个hycall的方法
Function.prototype.hycall = function(thisArg, ...args) {
// 在这里可以去执行调用的那个函数(foo)
// 问题: 得可以获取到是哪一个函数执行了hycall
// 1.获取需要被执行的函数
var fn = this
// 2.对thisArg转成对象类型(防止它传入的是非对象类型)
thisArg = (thisArg !== null && thisArg !== undefined) ? Object(thisArg): window
// 3.调用需要被执行的函数
thisArg.fn = fn
var result = thisArg.fn(...args)
delete thisArg.fn
// 4.将最终的结果返回出去
return result
}
2、bind
Function.prototype.hybind = function(thisArg, ...argArray) {
// 1.获取到真实需要调用的函数
var fn = this
// 2.绑定this
thisArg = (thisArg !== null && thisArg !== undefined) ? Object(thisArg): window
function proxyFn(...args) {
// 3.将函数放到thisArg中进行调用
thisArg.fn = fn
// 特殊: 对两个传入的参数进行合并
var finalArgs = [...argArray, ...args]
var result = thisArg.fn(...finalArgs)
delete thisArg.fn
// 4.返回结果
return result
}
return proxyFn
}
3、apply(和call没啥区别)忽略