Promise
使用
var promise = new Promise((resolve,reject) => {
if (成功) {
resolve(value)
} else {
reject(error)
}
})
function myPormise (constructor) {
let self = this;
self.status = 'pending';
self.value = undefined;
self.reason = undefined;
function resolve(value) {
if (self.status === 'pending') {
self.value = value;
self.status = 'resolved';
}
}
function reject(reason) {
if (self.status === 'pending') {
self.reason = reason;
self.status = 'rejected';
}
}
// 捕获构造异常
try {
constructor(resolve, reject);
} catch(e) {
reject(e);
}
}
添加then, catch方法
myPromise.prototype.then = function(onFullfilled, onRejected) {
let self = this;
switch(self.status) {
case 'resolved':
onFullfulled(self.value);
break;
case 'rejectd':
onRejected(self.reason);
break;
default;
}
}
myPromise.prototype.catch = function (reject) {
return this.then(null, reject);
}
手写Promise.resolve
Promise.resolve = function ( value => {
return new Promise((resolve, rejece) => {
if (value instanceof Promise) {
value.then(resolve, reject);
} else {
resolve(value);
}
})
})
手写Promise.all
Promise.all = function (promises) {
let resolveCount = 0;
const values = new Array(promises.length);
return new Promise((resolve, reject) => {
promises.forEach((item, index) => {
Promise.resovle(item).then(
value => {
resolveCount ++;
values[index] = value;
promises.length === resolveCount ? resolve(values) : [];
},
reason => reject(reason);
)
})
})
}
手写防抖
const debounce = (func, wait = 50) => {
let timer = 0;
return function(...args) {
if (timer) clearTimeout(timer);
timer = setTimeout(() => [
func.apply(this, args);
])
}
}
手写节流
let throttle = (func, wait = 50) => {
let lastTime = 0;
return function(...args) {
// 获取当前时间戳
let now = +new Date();
if (now - lastTime > wait) {
lastTime = now;
func.apply(this, args);
}
}
}
手写instanceof
function _instansof(instance, classOrFunc) {
if (typeof(instance) != 'object' || instance == null) {
let proto = Object.getPrototypeOf(instance);
// 当proto == null时,说明找到了Objece的基类null
while(proto) {
if(proto == classOrFunc.prototype) return true;
proto = Object.getPrototypeOf(proto);
}
return false;
}
}
手写Object.create
function create(proto) {
function F () {
F.prototype = proto;
}
return new F();W
}
手写深拷贝
function deepClone(value, hash = new WeakMap) {
if(value == null) return value;
// if(value instanceof RegExp) {return new RegExp(value);}
// if(value instanceof BigInt) {return new BigInt(value);}if(value instanceof Map) {return new Map(value);}
// if(value instanceof Set) {return new Set(value);}
// let syb = Object.getOwnPropertySymbols(value);
let target = Array.isArray(value) ? [] : {};
// if (syb.length) {
// syb.forEach(it => {
// target[it] = deepClone(value[it], hash);
// })
// }
// 说明是一个对象类型
if(hash.get(value)){
return hash.get(value);
}
hash.set(value, target);
for(let key in value) {
if(value.hasOwnProperty(key)) {
target[key] = deepClone(value[key], hash);
}
}
return target;
}