手写 New 关键字
function MyNew(fn, ...param) {
let obj = {};
obj._proto__ = fn.prototype;
const result = fn.apply(obj, param)
return typeof result === "object" ? result : obj
}
function fun(a, b, c) {
console.log(a, b, c)
this.name = "小米"
}
const obj = MyNew(fun, 1, 2, 3)
console.log(obj)
手写 instanceof 方法
function MyInstanceof(value, target) {
const types = ["function", "object"]
if (!types.includes(typeof value) || value === null) {
return false
}
let pro = Object.getPrototypeOf(value)
while (true) {
if (pro === null) {
return false
}
if (pro === target.prototype) {
return true
}
pro = Object.getPrototypeOf(pro)
}
}
console.log(MyInstanceof({}, Object))
console.log(MyInstanceof(1, Number))
手写 call 方法
Function.prototype.myCall = function (param) {
const obj = param || window;
obj.fn = this;
const args = [...arguments].splice(1);
const result = obj.fn(...args)
return result
}
function fun(a, b, c) {
console.log(a, b, c, this)
}
const obj = {
name: "小明"
}
fun.myCall(obj, 1, 2, 3)
手写 apply 方法
Function.prototype.myApply = function (param) {
const obj = param || window;
obj.fn = this;
const args = arguments[1];
const result = obj.fn(...args)
return result
}
function fun(a, b, c) {
console.log(a, b, c, this)
}
const obj = {
name: "小明"
}
fun.myApply(obj, [1, 2, 3])
手写深克隆方法
function _clone(target) {
if (typeof target !== "object" || target === null) {
return target
}
let obj;
if (target instanceof Array) {
obj = []
} else if (target instanceof Date) {
obj = new Date(target)
} else if (target instanceof RegExp) {
obj = new RegExp(target)
} else {
obj = {}
}
for (let key in target) {
obj[key] = _clone(target[key])
}
const symbolKeys = Object.getOwnPropertySymbols(target);
for (let symKey of symbolKeys) {
obj[symKey] = _clone(target[symKey])
}
return obj
}
const obj = {
a: 1,
b: 2,
c: {
d: 3,
e: 4
},
f: [1, 2, 3],
g: new Date(),
h: /a/,
i: Symbol('a')
}
const obj1 = _clone(obj)
const obj2 = obj
console.log(obj1 === obj)
console.log(obj2 === obj)
并发请求 每次发送3个实现方式
function concurrence(urls, maxNum) {
return new Promise((resolve, reject) => {
const result = [];
let index = 0;
let count = 0;
async function run() {
const url = urls[index]
const i = index;
index++
try {
const res = await fetch(url)
result[i] = res
} catch (error) {
result[i] = error
} finally {
count++;
if (count === urls.length) {
resolve(result)
}
if (index < urls.length) {
run()
}
}
}
for (let i = 0; i < Math.min(urls.length, maxNum); i++) {
run()
}
})
}
const arr = Array.from({ length: 10 }).map(item => "https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.js")
concurrence(arr, 3).then(res => {
console.log(res)
})