1.深克隆
// 手写深拷贝
function cloneDeep(obj) {
if (typeof obj !== 'object' || obj === null) return obj
const newObj = Array.isArray(obj) ? [] : {}
for(const [k, v] of Object.entries(obj)) {
newObj[k] = cloneDeep(v)
}
return newObj
}
var a = {a: {b: [1]}}
var b = cloneDeep(a)
b.a.b[0] = 2
console.log(a, b)
2.reduce
Array.prototype.myReduce = function (fn, defaultData) {
const hasDefault = defaultData !== undefined // 第二个参数不传, 初始pre取arr[0], 初始curr取arr[1]
let pre = hasDefault ? defaultData : this[0]
this.forEach((item, index) => {
if (index === 0 && !hasDefault) return
pre = fn(pre, item , index, this)
})
return pre
}
var a = [1, 3, 5].myReduce((pre, curr) => pre + curr)
console.log(a) // 9
3.call apply
// call无非是改变this指向,但其实也可以理解成, b本没有这个方法,
// 现在call一下, 就等于将a方法写进b里面然后执行, 然后this执行普通函数时, 谁调用我我就指向谁
// 所以this就指向了b
Function.prototype.myCall = function(ctx, ...args) {
ctx.fn = this // this === foo
const res = ctx.fn(...args)
delete ctx.fn
return res
}
var a = { prop: 111, foo(...args) { console.log(this.prop, ...args); return 333 } }
var b = { prop: 222 }
a.foo.myCall(b, '实参1', '实参2')
// 和上面原理一羊, apply传参格式是数组
Function.prototype.myApply = function(ctx, args) {
ctx.fn = this
const res = ctx.fn(...args)
delete ctx.fn
return res
}
var a = { prop: 111, foo(...args) { console.log(this.prop, ...args); return 333 } }
var b = { prop: 222 }
a.foo.myApply(b, ['实参1', '实参2'])
4.bind
// bind和call原理差不多, 无非就是多了一个闭包, 用来缓存变量
Function.prototype.myBind = function(ctx, ...args1) {
ctx.fn = this
return (...arg2) => {
const res =ctx.fn(...args1, ...arg2)
delete ctx.fn
return res
}
}
var a = { prop: 111, foo(...args) { console.log(this.prop, ...args); return 333 } }
var b = { prop: 222 }
a.foo.myBind(b, '实参1', '实参2')('实参3', '实参4')
6.promise(乞丐版)
class MyPromise {
constructor(cb) {
this.status = 'pending'
cb(this.resolve, this.reject)
}
resolve = (data) => {
this.status = 'fulfilled'
this.data = data
this.thenCb(this.data)
}
reject = (err) => {
this.status = 'rejected'
this.data = err
}
then(cb){
this.thenCb = cb
}
}
var promise = new MyPromise((resolve, reject) =>
setTimeout(() => resolve(111), 3000)).then(res => console.log(res))
7.防抖节流
// 防抖
function debounce(fn, delay) {
let timer
return (...args) => {
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
fn.apply(this, args)
}, delay)
}
}
// 节流
function throttle(fn, delay) {
let timer
return (...args) => {
if (timer) return
timer = setTimeout(() => {
fn.apply(this, args)
timer = false
}, delay)
}
8.new
function myNew(Func, ...args) {
const instance = {};
Func.call(instance, ...args)
instance.__proto__ = Func.prototype
return instance
}
9.Object.create
// 创建一个空对象, {}.__proto__ === protoObj
function create(protoObj) {
function F() {}
F.prototype = protoObj;
return new F();
}
10. 柯里化
function curry(func) {
return curried(...args) {
if (args.length >= func.length) {
return func.apply(this, args)
}
return function (...args2) {
return curried.call(this, {...args, ...args2}))
}
}
}
// 测试
function sum (a, b, c) {
return a + b + c
}