前端面试题分享:fn1.call.call(fn2)
function fn1() { console.log(1) } function fn2() { console.log(2) } fn1.call(fn2) // 此处打印结果 fn1.call.call(fn2) // 此处打印结果
思路:自己实现call方法,根据实现过程中了解打印结果出现的原因。
Function.prototype.mycall = function my(context, ...args) {
// context -> window
// ??表示只有context的值是undefined或null时才会返回window
context = context ?? window
context.fn = this
const result = context.fn(...args)
delete context.fn
return result
}
fn1.mycall(fn2) // 打印结果1
fn1.mycall.mycall(fn2) // 打印结果2
fn1.mycall.mycall(fn2)调用中,首先调用mycall(fn2),调用过程中,首先参数context接收到的是fn2,this指向的值为f my(context, ...args),然后在第二次执行context.fn(...args)时,实际执行的是fn2.my(context, ...args),代码再次调用function my(context, ...args),再次调用时context接受的是空数组,所以判断结果为context=window,所以内部指向为context.fn = this,实际为window.fn = fn2(),因此代码最后执行的实际调用为:window.fn2(),其结果自然是2。
如果对过程不是很明白的话,可以再浏览器中进行调试,一步步F11进行调试,过程就很清晰了,如果本文章有帮助到你,可以再评论区写下你的观点~