// myNew
function myNew(fn,...args){
let obj = {}
let res = fn.apply(obj,args)
obj.__proto__ = fn.prototype
return res instanceof Object ? res : obj
}
function myall(arr){
return new Promise((resolve,reject) => {
if(!Array.isArray(arr)) throw('参数必须为数组')
let res = []
let len = arr.length;
let count = 0
for(let i = 0; i < len; i++){
Promise.resolve(arr[i])
.then(val => {
arr[i] = val
count++
if(count === lent) resolve(res)
})
.catch(e => console.log(e))
}
})
}
function race(arr){
return new Promise((resolve,reject) => {
if(!Array.isArray(arr)) throw('xx')
for(let i = 0; i < arr.length; i++){
Promise
.resolve(arr[i])
.then(val => resolve(val))
.catch(e => reject(e))
}
})
}
function debounce(fn,delay){
let timer;
return function(){
if(timer) clearTimeout(timer)
timer = setTimeout(() => {
fn.apply(this,arguments)
},delay)
}
}
- 立即执行
function pdeounce(fn,delay,immediate){
let timer,context,params;
later = () => {
timer = null
setTimeout(() => {
if(!immediate) fn(context,params)
context = params = null
},delay)
}
return function(...args){
if(!timer){
timer = later()
if(immediate) fn.apply(this,args)
else{
context = this
params = args
}
}else{
clearTimeout(timer)
timer = later()
}
}
}
- 节流
function throttle(fn,time){
let time = 0;
return function(...args){
let timeNow = Date.now()
if(timeNow - time > delay){
fn.apply(this,args)
time = timeNow
}
}
}
- call
function mycall(obj,...args){
obj.fn = this
obj.fn(...args)
delete obj.fn
}
// 实现create(obj),实现以obj为原型
- create
function create(obj){
function fn(){}
fn.prototype = obj
return new fn()
}
- 浅拷贝
function easyCopy(obj){
const res = obj
return res
}
function easyCopy(obj){
return Object.assign({},obj)
}
function deepCopy(obj){
return JSON.parse(JSON.stringify(obj))
}
function deepCopyD(obj){
let copy = Array.isArray(obj) ? [] : {}
for(let key in obj){
if(obj.hasOwnPropperty(key)){
copy[key] = typeof obj[key] === 'object' ? deepCopyD(obj[key]): obj[key]
}
}
return copy
}