当前位置:网站首页>js面试题:fn.call.call.call.call(fn2) 解析
js面试题:fn.call.call.call.call(fn2) 解析
2022-04-23 05:54:00 【迷失的骆驼】
有这样一道 JS面试题,问 fn.call.call.call.call(fn2)
的结果是什么?
先说下 call 函数的内部原理:
- 可以改变函数的this;
- 执行函数
下面模拟下 原生的call函数:
Function.prototype.call = function(context, ...args){
context = context? Object(context) : window;
// 改变 this
context.fn = this;
// 执行函数
return context.fn(...args);
}
如下:
function fn(){
console.log(11)
}
function fn2(){
console.log(22)
}
问:
fn.call.call.call.call(fn2) 的结果是什么?
解析:
- 前面的一串
fn.call.call.call.call
并没有调用,只是获取对象的call属性,所以,这一串的结果是 Function.call 属性。 - 所以那一串 就是
Function.call.call(fn2)
;还可以解理为 fn3.call(fn2)。 - 根据call的原理(可参考上面的call模拟),在 fn3执行call,其实际是这样执行的
fn2.fn3()
。 - 由于 fn3实际上就是 call 函数,所以, fn2.fn3() 等价于
fn2.call()
。 - 所以,上面那一串代码的最终结果,就是调用 fn2,所以结果输出 22.
版权声明
本文为[迷失的骆驼]所创,转载请带上原文链接,感谢
https://blog.csdn.net/xufang461010923/article/details/108111226
边栏推荐
猜你喜欢
随机推荐
Eigen 学习总结
C [document operation] PDF files and pictures are converted to each other
提交本地仓库并同步码云仓库
ES6新增方法
导入文件时候 new FormData()
20220222回归职场
逻辑回归原理及代码实现
Assembly base code example
token详解以及应用原理
ES6
[UDS unified diagnosis service] i. diagnosis overview (3) - ISO 15765 architecture
Understanding of SSH public key and private key
特效案例收集:鼠标星球小尾巴
[UDS unified diagnostic service] III. application layer protocol (1)
Latex configuration and use
MOS管特性和导通过程
VHDL-任意分频器(50%占空比)
汇编 32位无符号加法计算器
Error in created hook: “ReferenceError: “Promise”未定义“
[UDS unified diagnosis service] IV. typical diagnosis service (1) - diagnosis and communication management function unit