【js手写】熟悉的陌生人👋

2021-06-25  本文已影响0人  Adder

为什么常常会被问到“手写XXXX”;其实就能验证出,除了日常使用插件🖋,是否明白其中原理...
这里记录一下手写的各种情况🧐

手写ajax

基于XMLHttpRequest的封装,通用的请求方法

function ajax(url, method){
    return new Promise((resolve, reject) => {
        const request = new XMLHttpRequest();
        request.open(method, url);
        request.onreadystatechange = () => {
            if (request.status === 200 &&request.readyState === 4) {
                resolve(request.response)
                // success
            } else {
                reject(request)
                // faild
            }
        }
        request.send()
    })
}

手写new方法

function _new(fn, ...arg) {
    var obj = Object.create(fn.prototype);
    const result = fn.apply(obj, arg);
    console.log(result)
    return Object.prototype.toString.call(result) == '[object Object]' ? result : obj;
}
// 构造函数
function Person (name){
  this.name = name;
}
// 生成实例
const p1 = _new(Person, 'lilli')
// p1 :  {name: 'lili'}

手写深拷贝

function _deepclone(object) {
  // 判断传入的参数是数组还是对象
  if (!(object instanceof Array) && !(object instanceof Object)) {
    return object;
  }
  let target = object instanceof Array ? []: {}
  for (const [k ,v] of Object.entries(object)) {
    target[k] = typeof v == 'object' ? _deepclone(v) : v
  }
  return target
}

手写数组去重

// 1th
function unique (arr) {
    return arr.filter((item, idx, self) => self.indexOf(item) === idx);
}
// 2th
function unique(arr) {
  return arr.reduce((a, b) => {
    return a.includes(b) ? a : a.concat(b)
  }, [])
}
// 3th 

利用对象的属性不能相同的特点进行去重

const testArr = [{name: 'mary', value: 1},{name: 'mary', value: 1},{name: 'jonh', value: 2}]
const obj = {};
const res = [];
testArr.forEach((item) => {
    if (!obj[item.name]) {
        res.push(item);
       obj[item.name] = item.value;
    }
})
console.log(res)
//结果
[ {
  name: "mary",
  value: 1
}, {
  name: "jonh",
  value: 2
}]

手写数组扁平化

function _flatArr (testArr) {
    let res = [];
    for(let i=0; i< testArr.length; i+=1) {
        if (Object.prototype.toString.call((testArr[i])).slice(8, -1) === 'Array'){
            res = _flatArr (testArr[i]).concat(res);
        } else {
            res.push(testArr[i])
        }
    }
    return res;
}

手写instanceof

/**
L:左边(参数)
R:右边(预判类型)
**/
function instance_of(L, R) {
   if (['string','number','undefined','boolean','symbol'].includes(typeof(L))) {
       return false;
   }
   if (L === null) return false;

   let R_prototype = R.prototype;
   L = L.__proto__;
   while(true) {
       if (L === R_prototype) {
           return true;
       }
       if (L === null) {
           return false;
       }
       L = L.__proto__;
   }
}

手写防抖

场景:窗口改变大小触发方法

function debounce (fn, delay) {
    console.log('debounce')
    let timer = null;
    return function (){
        if (timer) {
            window.clearTimeout(timer)
        }
        timer = window.setTimeout(() =>{
            fn.apply(this, arguments);
            timer = null;
        }, delay)
    }
}

function fnfasly () {
    console.log('resize----', (new Date()).valueOf())
}

const realfn = debounce(fnfasly, 1000)
function listenResize () {
    window.addEventListener('resize', () => {
        realfn()
    })
} 

listenResize();

手写节流

场景:窗口改变大小触发方法

function throttle(fn, delay) {
    let canuse = true;
    return function (){
        if (!canuse) return;
        canuse = false;
        fn.apply(this, arguments);
        setTimeout(() => {
            canuse = true;
        }, delay)
        
    }
}

let realfn = throttle(() => {console.log('throttle-resize', +new Date())}, 1000)

function listenResize () {
    window.addEventListener('resize', () => {
        realfn()
    })
} 

listenResize()

手写原型继承

function Animal(color) {
    this.color = color
}
Animal.prototype.move = function() {}
// 动物可以动
function Dog(color, name) {
    Animal.call(this, color)
    // 或者 Animal.apply(this, arguments)
    this.name = name
}
// 下面三行实现 Dog.prototype.__proto__ = Animal.prototype
function temp() {}
temp.prototype = Animal.prototype
Dog.prototype = new temp()

Dog.prototype.constuctor = Dog
// 这行看不懂就算了,面试官也不问
Dog.prototype.say = function() {
    console.log('汪')
}

var dog = new Dog('黄色','阿黄')
🐕

手写排序算法

之前的文章里有写过:

用reduce手写一个map

分析:
map接收两个参数:

  1. 回调方法,该方法的入参包括(item,index,self)
  2. 执行回调时候的this(如果回调是箭头函数,第二个参数就是外层代码块的this或者global)

map返回内容:
数组的每项,经过回调函数处理之后,的返回值组成的数组

Array.prototype.nMap = function (callbackFn, thisArg) {
const result = [];
this.reduce((prev, current, index, array) => {
    result[index] = callbackFn.call(thisArg, array[index], index, array);
}, 0)
return result;
}

使定时器没有回调

定时器没有回调,意思就是不需要处理任务,只需要等“一秒”,类似于sleep
分析:定时器是异步的,因此可以使用promise来构建

let delay = (time) => new Promise((resolve) => { setTimeout(resolve, time) })
console.log(111)
await delay(1000)
// 一秒后打印222
console.log(222)

😶简书为啥没有锚点导航?


上一篇 下一篇

猜你喜欢

热点阅读