手写一个promise
console.log(1);
class myPromise1 {
static PENDING = 'pending';
static FULFILLED = 'fulfilled';
static REJECTED = 'rejected';
constructor(func) {
this.PromiseState = myPromise1.PENDING;
this.PromiseResult = null;
this.onFulfilledCallbacks=[]
this.onRejectedCallbakcs=[]
try{
func(this.resolve.bind(this), this.reject.bind(this));
} catch (error) {
this.reject(error)
}
}
resolve(result) {
if (this.PromiseState === myPromise1.PENDING) {
setTimeout(() => {
this.PromiseState = myPromise1.FULFILLED;
this.PromiseResult = result;
this.onFulfilledCallbacks.forEach(callback=>{
callback(result)
})
});
}
}
reject(reason) {
if (this.PromiseState === myPromise1.PENDING) {
setTimeout(() => {
this.PromiseState = myPromise1.REJECTED;
this.PromiseResult = reason;
this.onRejectedCallbakcs.forEach(callback=>{
callback(reason)
})
});
}
}
then(onFulfilled, onRejected) {
onFulfilled =typeof onFulfilled==='function'?onFulfilled:value=>value
onRejected =typeof onRejected==='function'?onRejected:reason=>{
throw reason
}
if (this.PromiseState === myPromise1.PENDING) {
this.onFulfilledCallbacks.push(onFulfilled)
this.onRejectedCallbakcs.push(onRejected)
}
if (this.PromiseState === myPromise1.FULFILLED) {
setTimeout(() => {
onFulfilled(this.PromiseResult);
});
}
if (this.PromiseState === myPromise1.REJECTED) {
setTimeout(() => {
onRejected(this.PromiseResult);
});
}
}
}
// 测试代码
let promise1 = new myPromise1((resolve, reject) => {
console.log(2);
setTimeout(() => {
console.log('A',promise1.PromiseState);
resolve('aaa')
console.log('B',promise1.PromiseState);
console.log(4);
});
})
promise1.then(
result => {
console.log('C',promise1.PromiseState);
console.log('fulfiiled:', result)
return result
},
reason => {
console.log('rejected:', reason)
}
)
console.log(3);
class类 静态static调用不能在实例上调用,而应通过类本身。
class Foo{
static bar(){
this.baz()
}
static baz(){
console.log('hello')
}
baz(){
console.log('hello2')
}
}
console.log(Foo.bar())//hello
继承
使用super方法在static即可调用父类方法,也就是我们extends的对象。注意的是,能调用的也是父类中的static
class Foo{
static classMethod(){
return 'hello'
}
}
class Bar extends Foo{
static classMethod(){
return super.classMethod()+', too';
}
}
console.log(Bar.classMethod())
class类不存在变量提升