前端高频手撕代码整理
作者:互联网
1. 手写闭包
首先,看一个简单的案例:
1 for (var i = 0; i < 4; i++) { 2 setTimeout(() => { 3 console.log(i); 4 }, i * 1000); 5 } 6 // 每隔一秒打印 4 4 4 4
因为var 没有块级作用域,循环变量变成全局变量。如何解决?----> 闭包
1 for (var i = 0; i < 4; i++) { 2 (function(j) { 3 setTimeout(() => { 4 console.log(j); 5 }, j * 1000); 6 })(i) 7 } 8 // 每隔一秒打印 0 1 2 3
补:还可以通过let解决。
2. 手写实现call、apply、bind
(1)call
test.call(a)
call首先将test的this指向a,然后执行函数test。
我们可以将函数test挂载到a上面,让函数test变成a的一个方法,通过a.test来调用
1 Function.prototype.myCall = function(context) { 2 context = context || window; //没传入this 默认绑定window对象 3 context.fn = this; // 将myCall函数的调用者test挂载到context的属性上,可以通过context.fn调用test函数.这里的context就是a 4 const args = [...arguments].slice(1); // 将第一个参数去掉,即去掉test.myCall中的a,然后args=[1,2] 5 const results = context.fn(...args); // 去调用test(1,2) 6 delete context.fn 7 return results 8 } 9 10 function test(arg1, arg2) { 11 console.log(arg1, arg2); 12 console.log(this.name, this.offer); 13 } 14 const a = { 15 name: 'coder', 16 offer: 100 17 } 18 test.myCall(a, 1, 2)
1 2
coder 100
标签:console,log,前端,call,context,test,高频,myCall,代码 来源: https://www.cnblogs.com/coder-zero/p/14719680.html