常考的 JS 手写题
XPoet 前端鼓励师

前端面试中常考的 JS 手写题系列:

函数节流

function throttle(fn, delay) {
let preTime = Date.now()

return function () {
let ctx = this,
args = arguments,
nowTime = Date.now()

// 如果两次时间间隔超过了指定时间,则执行函数
if (nowTime - preTime >= delay) {
preTime = Date.now()
return fn.apply(ctx, args)
}

}
}

函数防抖

function debounce(fn, wait) {
let timer = null

return function () {
let ctx = this,
args = arguments

if (timer) {
clearTimeout(timer)
timer = null
}

timer = setTimeout(() => {
fn.apply(ctx, args)
}, wait)
}
}

深拷贝

function deepCopy(object) {
if (!object || typeof object !== 'object') {
return
}

let newObject = Array.isArray(object) ? [] : {}

for (let key in object) {
newObject[key] = typeof object[key] === 'object' ? deepCopy(object[key]) : object[key]
}
return newObject
}

call 函数

Function.prototype.myCall = function (ctx) {
// 判断调用对象
if (typeof this !== 'function') {
throw new TypeError('Error')
}

// 获取参数
let args = [...arguments].slice(1),
result = null

// 判断 ctx 是否传入,如果未传入,则设置为 window
ctx = ctx || window

// 将调用函数设为对象的方法
ctx.fn = this

// 调用函数
result = ctx.fn(...args)

// 将属性删除
delete ctx.fn

return result
}

apply 函数

bind 函数

整理中……

  • Post title:常考的 JS 手写题
  • Post author:XPoet
  • Create time:2022-01-06 20:59:55
  • Post link:https://xpoet.cn/2022/01/常考的-JS-手写题/
  • Copyright Notice:All articles in this blog are licensed under BY-NC-SA unless stating additionally.
 Comments