JavaScript中各种源码实现(前端面试笔试必备)

 前言

最近很多人和我一样在积极地准备前端的面试笔试,所以我也就整理了一些前端面试笔试中非常容易被问到的原生函数实现和各种前端原理实现。

创新互联网站建设由有经验的网站设计师、开发人员和项目经理组成的专业建站团队,负责网站视觉设计、用户体验优化、交互设计和前端开发等方面的工作,以确保网站外观精美、网站设计、成都网站制作易于使用并且具有良好的响应性。

能够手写实现各种JavaScript原生函数,可以说是摆脱API调用师帽子的第一步,我们不光要会用,更要去探究其实现原理!

对JavaScript源码的学习和实现能帮助我们快速和扎实地提升自己的前端编程能力。

实现一个new操作符

我们首先知道new做了什么:

  1. 创建一个空的简单JavaScript对象(即{});
  2. 链接该对象(即设置该对象的构造函数)到另一个对象 ;
  3. 将步骤(1)新创建的对象作为this的上下文 ;
  4. 如果该函数没有返回对象,则返回this。

知道new做了什么,接下来我们就来实现它

 
 
 
  1. function create(Con, ...args){ 
  2.   // 创建一个空的对象 
  3.   this.obj = {}; 
  4.   // 将空对象指向构造函数的原型链 
  5.   Object.setPrototypeOf(this.obj, Con.prototype); 
  6.   // obj绑定到构造函数上,便可以访问构造函数中的属性,即this.obj.Con(args) 
  7.   let result = Con.apply(this.obj, args); 
  8.   // 如果返回的result是一个对象则返回 
  9.   // new方法失效,否则返回obj 
  10.   return result instanceof Object ? result : this.obj; 

实现一个Array.isArray

 
 
 
  1. Array.myIsArray = function(o) {  
  2.   return Object.prototype.toString.call(Object(o)) === '[object Array]';  
  3. };  

实现一个Object.create()方法

 
 
 
  1. function create =  function (o) { 
  2.     var F = function () {}; 
  3.     F.prototype = o; 
  4.     return new F(); 
  5. }; 

实现一个EventEmitter

真实经历,最近在字节跳动的面试中就被面试官问到了,让我手写实现一个简单的Event类。

 
 
 
  1. class Event { 
  2.   constructor () { 
  3.     // 储存事件的数据结构 
  4.     // 为查找迅速, 使用对象(字典) 
  5.     this._cache = {} 
  6.   } 
  7.  
  8.   // 绑定 
  9.   on(type, callback) { 
  10.     // 为了按类查找方便和节省空间 
  11.     // 将同一类型事件放到一个数组中 
  12.     // 这里的数组是队列, 遵循先进先出 
  13.     // 即新绑定的事件先触发 
  14.     let fns = (this._cache[type] = this._cache[type] || []) 
  15.     if(fns.indexOf(callback) === -1) { 
  16.       fns.push(callback) 
  17.     } 
  18.     return this 
  19.     } 
  20.  
  21.   // 解绑 
  22.   off (type, callback) { 
  23.     let fns = this._cache[type] 
  24.     if(Array.isArray(fns)) { 
  25.       if(callback) { 
  26.         let index = fns.indexOf(callback) 
  27.         if(index !== -1) { 
  28.           fns.splice(index, 1) 
  29.         } 
  30.       } else { 
  31.         // 全部清空 
  32.         fns.length = 0 
  33.       } 
  34.     } 
  35.     return this 
  36.   } 
  37.   // 触发emit 
  38.   trigger(type, data) { 
  39.     let fns = this._cache[type] 
  40.     if(Array.isArray(fns)) { 
  41.       fns.forEach((fn) => { 
  42.         fn(data) 
  43.       }) 
  44.     } 
  45.     return this 
  46.   } 
  47.  
  48.   // 一次性绑定 
  49.   once(type, callback) { 
  50.     let wrapFun = () => { 
  51.       callback.call(this); 
  52.       this.off(type, callback); 
  53.     }; 
  54.     this.on(wrapFun, callback); 
  55.     return this; 
  56.   } 
  57.  
  58. let e = new Event() 
  59.  
  60. e.on('click',function(){ 
  61.   console.log('on') 
  62. }) 
  63. e.on('click',function(){ 
  64.   console.log('onon') 
  65. }) 
  66. // e.trigger('click', '666') 
  67. console.log(e) 

实现一个Array.prototype.reduce

首先观察一下Array.prototype.reduce语法

 
 
 
  1. Array.prototype.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue]) 

然后就可以动手实现了:

 
 
 
  1. Array.prototype.myReduce = function(callback, initialValue) { 
  2.   let accumulator = initialValue ? initialValue : this[0]; 
  3.   for (let i = initialValue ? 0 : 1; i < this.length; i++) { 
  4.     let _this = this; 
  5.     accumulator = callback(accumulator, this[i], i, _this); 
  6.   } 
  7.   return accumulator; 
  8. }; 
  9.  
  10. // 使用 
  11. let arr = [1, 2, 3, 4]; 
  12. let sum = arr.myReduce((acc, val) => { 
  13.   acc += val; 
  14.   return acc; 
  15. }, 5); 
  16.  
  17. console.log(sum); // 15 

实现一个call或apply

先来看一个call实例,看看call到底做了什么:

 
 
 
  1. let foo = { 
  2.   value: 1 
  3. }; 
  4. function bar() { 
  5.   console.log(this.value); 
  6. bar.call(foo); // 1 

从代码的执行结果,我们可以看到,call首先改变了this的指向,使函数的this指向了foo,然后使bar函数执行了。

总结一下:

  1. call改变函数this指向
  2. 调用函数

思考一下:我们如何实现上面的效果呢?代码改造如下:

 
 
 
  1. Function.prototype.myCall = function(context) { 
  2.   context = context || window; 
  3.   //将函数挂载到对象的fn属性上 
  4.   context.fn = this; 
  5.   //处理传入的参数 
  6.   const args = [...arguments].slice(1); 
  7.   //通过对象的属性调用该方法 
  8.   const result = context.fn(...args); 
  9.   //删除该属性 
  10.   delete context.fn; 
  11.   return result 
  12. }; 

我们看一下上面的代码:

  1. 首先我们对参数context做了兼容处理,不传值,context默认值为window;
  2. 然后我们将函数挂载到context上面,context.fn = this;
  3. 处理参数,将传入myCall的参数截取,去除第一位,然后转为数组;
  4. 调用context.fn,此时fn的this指向context;
  5. 删除对象上的属性 delete context.fn;
  6. 将结果返回。

以此类推,我们顺便实现一下apply,唯一不同的是参数的处理,代码如下:

 
 
 
  1. Function.prototype.myApply = function(context) { 
  2.   context = context || window 
  3.   context.fn = this 
  4.   let result 
  5.   // myApply的参数形式为(obj,[arg1,arg2,arg3]); 
  6.   // 所以myApply的第二个参数为[arg1,arg2,arg3] 
  7.   // 这里我们用扩展运算符来处理一下参数的传入方式 
  8.   if (arguments[1]) { 
  9.     result = context.fn(…arguments[1]) 
  10.   } else { 
  11.     result = context.fn() 
  12.   } 
  13.   delete context.fn; 
  14.   return result 
  15. }; 

以上便是call和apply的模拟实现,唯一不同的是对参数的处理方式。

实现一个Function.prototype.bind

 
 
 
  1. function Person(){ 
  2.   this.name="zs"; 
  3.   this.age=18; 
  4.   this.gender="男" 
  5. let obj={ 
  6.   hobby:"看书" 
  7. //  将构造函数的this绑定为obj 
  8. let changePerson = Person.bind(obj); 
  9. //  直接调用构造函数,函数会操作obj对象,给其添加三个属性; 
  10. changePerson(); 
  11. //  1、输出obj 
  12. console.log(obj); 
  13. //  用改变了this指向的构造函数,new一个实例出来 
  14. let p = new changePerson(); 
  15. // 2、输出obj 
  16. console.log(p); 

仔细观察上面的代码,再看输出结果。

我们对Person类使用了bind将其this指向obj,得到了changeperson函数,此处如果我们直接调用changeperson会改变obj,若用new调用changeperson会得到实例 p,并且其__proto__指向Person,我们发现bind失效了。

我们得到结论:用bind改变了this指向的函数,如果用new操作符来调用,bind将会失效。

这个对象就是这个构造函数的实例,那么只要在函数内部执行 this instanceof 构造函数 来判断其结果是否为true,就能判断函数是否是通过new操作符来调用了,若结果为true则是用new操作符调用的,代码修正如下:

 
 
 
  1. // bind实现 
  2. Function.prototype.mybind = function(){ 
  3.   // 1、保存函数 
  4.   let _this = this; 
  5.   // 2、保存目标对象 
  6.   let context = arguments[0]||window; 
  7.   // 3、保存目标对象之外的参数,将其转化为数组; 
  8.   let rest = Array.prototype.slice.call(arguments,1); 
  9.   // 4、返回一个待执行的函数 
  10.   return function F(){ 
  11.     // 5、将二次传递的参数转化为数组; 
  12.     let rest2 = Array.prototype.slice.call(arguments) 
  13.     if(this instanceof F){ 
  14.       // 6、若是用new操作符调用,则直接用new 调用原函数,并用扩展运算符传递参数 
  15.       return new _this(...rest2) 
  16.     }else{ 
  17.       //7、用apply调用第一步保存的函数,并绑定this,传递合并的参数数组,即context._this(rest.concat(rest2)) 
  18.       _this.apply(context,rest.concat(rest2)); 
  19.     } 
  20.   } 
  21. }; 

实现一个JS函数柯里化

Currying的概念其实并不复杂,用通俗易懂的话说:只传递给函数一部分参数来调用它,让它返回一个函数去处理剩下的参数。

 
 
 
  1. function progressCurrying(fn, args) { 
  2.  
  3.     let _this = this 
  4.     let len = fn.length; 
  5.     let args = args || []; 
  6.  
  7.     return function() { 
  8.         let _args = Array.prototype.slice.call(arguments); 
  9.         Array.prototype.push.apply(args, _args); 
  10.  
  11.         // 如果参数个数小于最初的fn.length,则递归调用,继续收集参数 
  12.         if (_args.length < len) { 
  13.             return progressCurrying.call(_this, fn, _args); 
  14.         } 
  15.  
  16.         // 参数收集完毕,则执行fn 
  17.         return fn.apply(this, _args); 
  18.     } 

手写防抖(Debouncing)和节流(Throttling)

节流

防抖函数 onscroll 结束时触发一次,延迟执行

 
 
 
  1. function debounce(func, wait) { 
  2.   let timeout; 
  3.   return function() { 
  4.     let context = this; // 指向全局 
  5.     let args = arguments; 
  6.     if (timeout) { 
  7.       clearTimeout(timeout); 
  8.     } 
  9.     timeout = setTimeout(() => { 
  10.       func.apply(context, args); // context.func(args) 
  11.     }, wait); 
  12.   }; 
  13. // 使用 
  14. window.onscroll = debounce(function() { 
  15.   console.log('debounce'); 
  16. }, 1000); 

节流

节流函数 onscroll 时,每隔一段时间触发一次,像水滴一样

 
 
 
  1. function throttle(fn, delay) { 
  2.   let prevTime = Date.now(); 
  3.   return function() { 
  4.     let curTime = Date.now(); 
  5.     if (curTime - prevTime > delay) { 
  6.       fn.apply(this, arguments); 
  7.       prevTime = curTime; 
  8.     } 
  9.   }; 
  10. // 使用 
  11. var throtteScroll = throttle(function() { 
  12.   console.log('throtte'); 
  13. }, 1000); 
  14. window.onscroll = throtteScroll; 

手写一个JS深拷贝

乞丐版

 
 
 
  1. JSON.parse(JSON.stringfy)); 

非常简单,但缺陷也很明显,比如拷贝其他引用类型、拷贝函数、循环引用等情况。

基础版

 
 
 
  1. function clone(target){ 
  2.   if(typeof target === 'object'){ 
  3.     let cloneTarget = {}; 
  4.     for(const key in target){ 
  5.       cloneTarget[key] = clone(target[key]) 
  6.     } 
  7.     return cloneTarget; 
  8.   } else { 
  9.     return target 
  10.   } 

写到这里已经可以帮助你应付一些面试官考察你的递归解决问题的能力。但是显然,这个深拷贝函数还是有一些问题。

一个比较完整的深拷贝函数,需要同时考虑对象和数组,考虑循环引用:

 
 
 
  1. function clone(target, map = new WeakMap()) { 
  2.   if(typeof target === 'object'){ 
  3.     let cloneTarget = Array.isArray(target) ? [] : {}; 
  4.     if(map.get(target)) { 
  5.       return target; 
  6.     } 
  7.     map.set(target, cloneTarget); 
  8.     for(const key in target) { 
  9.       cloneTarget[key] = clone(target[key], map) 
  10.     } 
  11.     return cloneTarget; 
  12.   } else { 
  13.     return target; 
  14.   } 

实现一个instanceOf

原理: L 的 proto 是不是等于 R.prototype,不等于再找 L.__proto__.__proto__ 直到 proto 为 null

 
 
 
  1. // L 表示左表达式,R 表示右表达式 
  2. function instance_of(L, R) { 
  3.     var O = R.prototype; 
  4.   L = L.__proto__; 
  5.   while (true) { 
  6.         if (L === null){ 
  7.             return false; 
  8.         } 
  9.         // 这里重点:当 O 严格等于 L 时,返回 true 
  10.         if (O === L) { 
  11.             return true; 
  12.         } 
  13.         L = L.__proto__; 
  14.   } 

实现原型链继承

 
 
 
  1. function myExtend(C, P) { 
  2.     var F = function(){}; 
  3.     F.prototype = P.prototype; 
  4.     C.prototype = new F(); 
  5.     C.prototype.constructor = C; 
  6.     C.super = P.prototype; 

实现一个async/await

原理

就是利用 generator(生成器)分割代码片段。然后我们使用一个函数让其自迭代,每一个yield 用 promise 包裹起来。执行下一步的时机由 promise 来控制

实现

 
 
 
  1. function _asyncToGenerator(fn) { 
  2.   return function() { 
  3.     var self = this, 
  4.       args = arguments; 
  5.     // 将返回值promise化 
  6.     return new Promise(function(resolve, reject) { 
  7.       // 获取迭代器实例 
  8.       var gen = fn.apply(self, args); 
  9.       // 执行下一步 
  10.       function _next(value) { 
  11.         asyncGeneratorStep(gen, resolve, reject, _next, _throw, 'next', value); 
  12.       } 
  13.       // 抛出异常 
  14.       function _throw(err) { 
  15.         asyncGeneratorStep(gen, resolve, reject, _next, _throw, 'throw', err); 
  16.       } 
  17.       // 第一次触发 
  18.       _next(undefined); 
  19.     }); 
  20.   }; 

实现一个Array.prototype.flat()函数

最近字节跳动的前端面试中也被面试官问到,要求手写实现。

 
 
 
  1. Array.prototype.myFlat = function(num = 1) { 
  2.   if (Array.isArray(this)) { 
  3.     let arr = []; 
  4.     if (!Number(num) || Number(num) < 0) { 
  5.       return this; 
  6.     } 
  7.     this.forEach(item => { 
  8.       if(Array.isArray(item)){ 
  9.         let count = num 
  10.         arr = arr.concat(item.myFlat(--count)) 
  11.       } else { 
  12.         arr.push(item) 
  13.       }   
  14.     }); 
  15.     return arr; 
  16.   } else { 
  17.     throw tihs + ".flat is not a function"; 
  18.   } 
  19. }; 

实现一个事件代理

这个问题一般还会让你讲一讲事件冒泡和事件捕获机制

 
 
 
  1.  
  2.     
  3. red
  4.  
  5.     
  6. yellow
  7.  
  8.     
  9. blue
  10.  
  11.     
  12. green
  13.  
  14.     
  15. black
  16.  
  17.     
  18. white
  19.  
  20.    
  21.    

实现一个双向绑定

Vue 2.x的Object.defineProperty版本

 
 
 
  1. // 数据 
  2. const data = { 
  3.   text: 'default' 
  4. }; 
  5. const input = document.getElementById('input'); 
  6. const span = document.getElementById('span'); 
  7. // 数据劫持 
  8. Object.defineProperty(data, 'text', { 
  9.   // 数据变化 —> 修改视图 
  10.   set(newVal) { 
  11.     input.value = newVal; 
  12.     span.innerHTML = newVal; 
  13.   } 
  14. }); 
  15. // 视图更改 --> 数据变化 
  16. input.addEventListener('keyup', function(e) { 
  17.   data.text = e.target.value; 
  18. }); 

Vue 3.x的proxy 版本

 
 
 
  1. // 数据 
  2. const data = { 
  3.   text: 'default' 
  4. }; 
  5. const input = document.getElementById('input'); 
  6. const span = document.getElementById('span'); 
  7. // 数据劫持 
  8. const handler = { 
  9.   set(target, key, value) { 
  10.     target[key] = value; 
  11.     // 数据变化 —> 修改视图 
  12.     input.value = value; 
  13.     span.innerHTML = value; 
  14.     return value; 
  15.   } 
  16. }; 
  17. const proxy = new Proxy(data, handler); 
  18.  
  19. // 视图更改 --> 数据变化 
  20. input.addEventListener('keyup', function(e) { 
  21.   proxy.text = e.target.value; 
  22. }); 

网站栏目:JavaScript中各种源码实现(前端面试笔试必备)
文章地址:http://www.hantingmc.com/qtweb/news48/17698.html

网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联