// 自己实现hyapply
Function.prototype.hyapply = function(thisArg, argArray) {
// 1.获取到要执行的函数
//这里的this是调用hyapply的函数
var fn = this
// 2.处理绑定的thisArg
//thisArg传入0时会算成没值thisArg = thisArg? Object(thisArg): window就不严谨了
thisArg = (thisArg !== null && thisArg !== undefined) ? Object(thisArg): window
// 3.执行函数
thisArg.fn = fn
var result
// 比较繁琐
// if (!argArray) { // argArray是没有值(没有传参数)
// result = thisArg.fn()
// } else { // 有传参数
// result = thisArg.fn(...argArray)
// }
// argArray = argArray ? argArray: []
argArray = argArray || []
result = thisArg.fn(...argArray)//...argArray不管有没有传参数argArray至少是一个空数组
delete thisArg.fn
// 4.返回结果
return result
}
function sum(num1, num2) {
console.log("sum被调用", this, num1, num2)
return num1 + num2
}
function foo(num) {
return num
}
function bar() {
console.log("bar函数被执行", this)
}
// 系统调用
//apply调用传的第二个参数必须为数组类型
// var result = sum.apply("abc", [20,30])
// console.log(result)
// 自己实现的调用
// var result = sum.hyapply("abc", [20, 30])
// console.log(result)
// var result2 = foo.hyapply("abc", [20])
// console.log(result2)
// edge case--特殊边缘判断
//没有传第二个参数
bar.hyapply(0)
//当传入的本身就有apply中的函数 为了防止函数被覆盖 用到es6的simple (独立符号永远不会重复)
bar.hyapply({fn:function(){}})
javaScript模拟实现apply
于 2022-03-25 11:14:01 首次发布