if (this.state === 'rejected') { queueMicrotask(() => { if (fail) fail(this.result); }); } }; }
console.log(1);
let my = newMyPromise((resolve, reject) => { console.log(2); setTimeout(() => { resolve(3); }, 1000); }); my.then((res) => { console.log(res); });
instanceof
理解 new 的时候发生什么 简单讲就是,构造函数有原型链指向这个构造函数的原型对象(这玩意就是构造函数写的一堆属性之类的) new 出来的对象也会有原型链指向那个原型对象
1 2 3 4 5 6 7 8
functionmyInstanceof(obj, constructor) { let proto = Object.getPrototypeOf(obj); while (proto) { if (proto === constructor.prototype) returntrue; proto = Object.getPrototypeOf(proto); } returnfalse; }
if (Array.isArray(value)) { let newArray = []; hash.set(value, newArray); return value.map((item) =>deepClone(item, hash)); }
if (typeStr === '[object Object]') { let newObj = {}; hash.set(value, newObj); for (let key ofObject.keys(value)) { newObj[key] = deepClone(value[key], hash); } return newObj; }
return value; }
手写 new
创建一个空对象然后设置成构成函数的原型
1 2 3 4 5 6 7
functionmyNew(constructor, ...args) { let obj = {}; Object.setPrototypeOf(obj, constructor.prototype); let result = constructor.apply(obj, args); if (typeof result === 'object' || typeof result === 'function') return result; return obj; }