前提基础:
1、对象调用的函数,这个函数里面的 this 指向是调用它的对象
2、arguments:这个属性是每个函数都有的一个伪类数组
<script>
;(
function() {
function myCall(context) {
// 基础:Object() 会根据传入参数的类型,返回其相应的对象,比如字符串会返回一个 String 对象
context = context ? Object(context) : window
// 提取传给函数的参数
let args = []
for(let i = 1 ; i < arguments.length ; i ++) {
args.push(arguments[i])
}
// 通过隐式绑定 this ,理解,只要 . 后面调用的函数,其里面的 this 都指向 . 前面的对象
// 而 调用 myCall 是通过 . 的方式调用的,所以 myCall 的 this 指向调用它的函数
// 通过 myCall 的 this 的值赋给 context 的属性,这样可以通过 context. 来调用函数,这样函数的 this 就执行 context 这个对象了
// 注意:不要 this() 执行函数,这样函数里面的 this 是指向 window
context.f = this
// 执行函数并接收返回值
let res = context.f(...args)
return res
}
Function.prototype.myCall = myCall
}
)()
function add(num) {
return this.name + num
}
let obj = {name: '天才'}
console.log(add.myCall(obj, 11));
</script>