【前端】一網打盡──前端進階和面試必會的8個手寫代碼
寫在前面
我們知道在前端進階和面試的時候,會考察到很多手寫源碼的問題,這些是通過學習和練習是可以掌握的,下面列舉了八個手寫的代碼系列,希望能夠對你有所幫助。
1 手寫Promise系列
在Promise的學習中,之前也寫過相關的分享文章,敬請參見《從小白視角上手Promise、Async/Await和手撕代碼》。
1.1 Promise.all
- //手寫promise.all
- Promise.prototype._all = promiseList => {
- // 當輸入的是一個promise列表
- const len = promiseList.length;
- const result = [];
- let count = 0;
- //
- return new Promise((resolve,reject)=>{
- // 循環遍歷promise列表中的promise事件
- for(let i = 0; i < len; i++){
- // 遍歷到第i個promise事件,判斷其事件是成功還是失敗
- promiseList[i].then(data=>{
- result[i] = data;
- count++;
- // 當遍歷到最后一個promise時,結果的數組長度和promise列表長度一致,說明成功
- count === len && resolve(result);
- },error=>{
- return reject(error);
- })
- }
- })
- }
1.2 Promise.race
- // 手寫promise.race
- Promise.prototype._race = promiseList => {
- const len = promiseList.length;
- return new Promise((resolve,reject)=>{
- // 循環遍歷promise列表中的promise事件
- for(let i = 0; i < len; i++){
- promiseList[i]().then(data=>{
- return resolve(data);
- },error=>{
- return reject(error);
- })
- }
- })
- }
1.3 Promise.finally
- Promise.prototype._finally = function(promiseFunc){
- return this.then(data=>Promise.resolve(promiseFunc()).then(data=>data)
- ,error=>Promise.reject(promiseFunc()).then(error=>{throw error}))
- }
2 手寫Aysnc/Await
- function asyncGenertor(genFunc){
- return new Promise((resolve,reject)=>{
- // 生成一個迭代器
- const gen = genFunc();
- const step = (type,args)=>{
- let next;
- try{
- next = gen[type](args);
- }catch(e){
- return reject(e);
- }
- // 從next中獲取done和value的值
- const {done,value} = next;
- // 如果迭代器的狀態是true
- if(done) return resolve(value);
- Promise.resolve(value).then(
- val=>step("next",val),
- err=>step("throw",err)
- )
- }
- step("next");
- })
- }
3 深拷貝
深拷貝:拷貝所有的屬性值,以及屬性地址指向的值的內存空間。
3.1 丟失引用的深拷貝
當遇到對象時,就再新開一個對象,然后將第二層源對象的屬性值,完整地拷貝到這個新開的對象中。
- // 丟失引用的深拷貝
- function deepClone(obj){
- // 判斷obj的類型是否為object類型
- if(!obj && typeof obj !== "object") return;
- // 判斷對象是數組類型還是對象類型
- let newObj = Array.isArray(obj) ? [] : {};
- // 遍歷obj的鍵值對
- for(const [key,value] of Object.entries(obj)){
- newObj[key] = typeof value === "string" ? deepClone(value) : value;
- };
- return newObj;
- }
3.2 終極方案的深拷貝(棧和深度優先的思想)
其思路是:引入一個數組 uniqueList 用來存儲已經拷貝的數組,每次循環遍歷時,先判斷對象是否在 uniqueList 中了,如果在的話就不執行拷貝邏輯了。
- function deepCopy(obj){
- // 用于去重
- const uniqueList = [];
- // 設置根節點
- let root = {};
- // 遍歷數組
- const loopList = [{
- parent: root,
- key: undefined,
- data: obj
- }];
- // 遍歷循環
- while(loopList.length){
- // 深度優先-將數組最后的元素取出
- const {parent,key,data} = loopList.pop();
- // 初始化賦值目標,key--undefined時拷貝到父元素,否則拷貝到子元素
- let result = parent;
- if(typeof key !== "undefined") result = parent[key] = {};
- // 數據已存在時
- let uniqueData = uniqueList.find(item=>item.source === data);
- if(uniqueData){
- parent[key] = uniqueData.target;
- // 中斷本次循環
- continue;
- }
- // 數據不存在時
- // 保存源數據,在拷貝數據中對應的引用
- uniqueList.push({
- source:data,
- target:result
- });
- // 遍歷數據
- for(let k in data){
- if(data.hasOwnProperty(k)){
- typeof data[k] === "object"
- ?
- // 下一次循環
- loopList.push({
- parent:result,
- key:k,
- data:data[k]
- })
- :
- result[k] = data[k];
- }
- }
- }
- return root;
- }
4 手寫一個單例模式
單例模式:保證一個類僅有一個實例,并提供一個訪問它的全局訪問點。實現方法一般是先判斷實例是否存在,如果存在直接返回,如果不存在就先創建再返回。
- // 創建單例對象,使用閉包
- const getSingle = function(func){
- let result;
- return function(){
- return result || (result = func.apply(this,arguments));
- }
- }
- // 使用Proxy攔截
- const proxy = function(func){
- let reuslt;
- const handler = {
- construct:function(){
- if(!result) result = Reflect.construct(func,arguments);
- return result;
- }
- }
- return new Proxy(func,hendler);
- }
5 手寫封裝一個ajax函數
- /*
- 封裝自己的ajax函數
- 參數1:{string} method 請求方法
- 參數2:{string} url 請求地址
- 參數2:{Object} params 請求參數
- 參數3:{function} done 請求完成后執行的回調函數
- */
- function ajax(method,url,params,done){
- // 1.創建xhr對象,兼容寫法
- let xhr = window.XMLHttpRequest
- ? new XMLHttpRequest()
- : new ActiveXObject("Microsoft.XMLHTTP");
- // 將method轉換成大寫
- method = method.toUpperCase();
- // 參數拼接
- let newParams = [];
- for(let key in params){
- newParams.push(`${key}=${params[k]}`);
- }
- let str = newParams.join("&");
- // 判斷請求方法
- if(method === "GET") url += `?${str}`;
- // 打開請求方式
- xhr.open(method,url);
- let data = null;
- if(method === "POST"){
- // 設置請求頭
- xhr.setRequestHeader(("Content-Type","application/x-www-form-urlencoded"));
- data = str;
- }
- xhr.send(data);
- // 指定xhr狀態變化事件處理函數
- // 執行回調函數
- xhr.onreadystatechange = function(){
- if(this.readyState === 4) done(JSON.parse(xhr.responseText));
- }
- }
6 手寫“防抖”和“節流”
在Promise的學習中,之前也寫過相關的分享文章,敬請參見《一網打盡──他們都在用這些”防抖“和”節流“方法》。
6.1 防抖
- /*
- func:要進行防抖處理的函數
- delay:要進行延時的時間
- immediate:是否使用立即執行 true立即執行 false非立即執行
- */
- function debounce(func,delay,immediate){
- let timeout; //定時器
- return function(arguments){
- // 判斷定時器是否存在,存在的話進行清除,重新進行定時器計數
- if(timeout) clearTimeout(timeout);
- // 判斷是立即執行的防抖還是非立即執行的防抖
- if(immediate){//立即執行
- const flag = !timeout;//此處是取反操作
- timeout = setTimeout(()=>{
- timeout = null;
- },delay);
- // 觸發事件后函數會立即執行,然后 n 秒內不觸發事件才能繼續執行函數的效果。
- if(flag) func.call(this,arguments);
- }else{//非立即執行
- timeout = setTimeout(()=>{
- func.call(this,arguments);
- },delay)
- }
- }
- }
6.2 節流
- // 節流--定時器版
- function throttle(func,delay){
- let timeout;//定義一個定時器標記
- return function(arguments){
- // 判斷是否存在定時器
- if(!timeout){
- // 創建一個定時器
- timeout = setTimeout(()=>{
- // delay時間間隔清空定時器
- clearTimeout(timeout);
- func.call(this,arguments);
- },delay)
- }
- }
- }
7 手寫apply、bind、call
7.1 apply
傳遞給函數的參數處理,不太一樣,其他部分跟call一樣。
apply接受第二個參數為類數組對象, 這里用了《JavaScript權威指南》中判斷是否為類數組對象的方法。
- Function.prototype._apply = function (context) {
- if (context === null || context === undefined) {
- context = window // 指定為 null 和 undefined 的 this 值會自動指向全局對象(瀏覽器中為window)
- } else {
- context = Object(context) // 值為原始值(數字,字符串,布爾值)的 this 會指向該原始值的實例對象
- }
- // JavaScript權威指南判斷是否為類數組對象
- function isArrayLike(o) {
- if (o && // o不是null、undefined等
- typeof o === 'object' && // o是對象
- isFinite(o.length) && // o.length是有限數值
- o.length >= 0 && // o.length為非負值
- o.length === Math.floor(o.length) && // o.length是整數
- o.length < 4294967296) // o.length < 2^32
- return true
- else
- return false
- }
- const specialPrototype = Symbol('特殊屬性Symbol') // 用于臨時儲存函數
- context[specialPrototype] = this; // 隱式綁定this指向到context上
- let args = arguments[1]; // 獲取參數數組
- let result
- // 處理傳進來的第二個參數
- if (args) {
- // 是否傳遞第二個參數
- if (!Array.isArray(args) && !isArrayLike(args)) {
- throw new TypeError('myApply 第二個參數不為數組并且不為類數組對象拋出錯誤');
- } else {
- args = Array.from(args) // 轉為數組
- result = context[specialPrototype](...args); // 執行函數并展開數組,傳遞函數參數
- }
- } else {
- result = context[specialPrototype](); // 執行函數
- }
- delete context[specialPrototype]; // 刪除上下文對象的屬性
- return result; // 返回函數執行結果
- };
7.2 bind
拷貝源函數:
- 通過變量儲存源函數
- 使用Object.create復制源函數的prototype給fToBind
返回拷貝的函數
調用拷貝的函數:
- new調用判斷:通過instanceof判斷函數是否通過new調用,來決定綁定的context
- 綁定this+傳遞參數
- 返回源函數的執行結果
- Function.prototype._bind = function (objThis, ...params) {
- const thisFn = this; // 存儲源函數以及上方的params(函數參數)
- // 對返回的函數 secondParams 二次傳參
- let fToBind = function (...secondParams) {
- const isNew = this instanceof fToBind // this是否是fToBind的實例 也就是返回的fToBind是否通過new調用
- const context = isNew ? this : Object(objThis) // new調用就綁定到this上,否則就綁定到傳入的objThis上
- return thisFn.call(context, ...params, ...secondParams); // 用call調用源函數綁定this的指向并傳遞參數,返回執行結果
- };
- if (thisFn.prototype) {
- // 復制源函數的prototype給fToBind 一些情況下函數沒有prototype,比如箭頭函數
- fToBind.prototype = Object.create(thisFn.prototype);
- }
- return fToBind; // 返回拷貝的函數
- };
7.3 call
根據call的規則設置上下文對象,也就是this的指向。
通過設置context的屬性,將函數的this指向隱式綁定到context上
通過隱式綁定執行函數并傳遞參數。
刪除臨時屬性,返回函數執行結果
- Function.prototype._call = function (context, ...arr) {
- if (context === null || context === undefined) {
- // 指定為 null 和 undefined 的 this 值會自動指向全局對象(瀏覽器中為window)
- context = window
- } else {
- context = Object(context) // 值為原始值(數字,字符串,布爾值)的 this 會指向該原始值的實例對象
- }
- const specialPrototype = Symbol('特殊屬性Symbol') // 用于臨時儲存函數
- context[specialPrototype] = this; // 函數的this指向隱式綁定到context上
- let result = context[specialPrototype](...arr); // 通過隱式綁定執行函數并傳遞參數
- delete context[specialPrototype]; // 刪除上下文對象的屬性
- return result; // 返回函數執行結果
- };
8 手寫繼承
8.1 構造函數式繼承
構造函數式繼承并沒有繼承父類原型上的方法。
- function fatherUser(username, password) {
- let _password = password
- this.username = username
- fatherUser.prototype.login = function () {
- console.log(this.username + '要登錄父親賬號,密碼是' + _password)
- }
- }
- function sonUser(username, password) {
- fatherUser.call(this, username, password)
- this.articles = 3 // 文章數量
- }
- const yichuanUser = new sonUser('yichuan', 'xxx')
- console.log(yichuanUser.username) // yichuan
- console.log(yichuanUser.username) // xxx
- console.log(yichuanUser.login()) // TypeError: yichuanUser.login is not a function
8.2 組合式繼承
- function fatherUser(username, password) {
- let _password = password
- this.username = username
- fatherUser.prototype.login = function () {
- console.log(this.username + '要登錄fatherUser,密碼是' + _password)
- }
- }
- function sonUser(username, password) {
- fatherUser.call(this, username, password) // 第二次執行 fatherUser 的構造函數
- this.articles = 3 // 文章數量
- }
- sonUser.prototype = new fatherUser(); // 第二次執行 fatherUser 的構造函數
- const yichuanUser = new sonUser('yichuan', 'xxx')
8.3 寄生組合繼承
上面的繼承方式有所缺陷,所以寫這種方式即可。
- function Parent() {
- this.name = 'parent';
- }
- function Child() {
- Parent.call(this);
- this.type = 'children';
- }
- Child.prototype = Object.create(Parent.prototype);
- Child.prototype.constructor = Child;
參考文章
- 《前端進階之必會的JavaScript技巧總結》
- 《js基礎-面試官想知道你有多理解call,apply,bind?[不看后悔系列]》