bind
Function.prototype.myBind = function(thisArg) {
if(typeof this !== 'function'){
return;
}
const that = this;
const args1 = Array.prototype.slice.call(arguments, 1);
return function() {
that.apply(thisArg, args1.concat(Array.prototype.slice.call(arguments)));
};
}
Promise
const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'
function MyPromise(executor) {
this.status = PENDING;
this.value = undefined;
this.reason = undefined;
this.onFulfilledCallbacks = [];
this.onRejectedCallbacks = [];
const that = this;
function resolve(value) {
if(that.status === PENDING){
that.status = FULFILLED;
that.status = FULFILLED;
that.value = value;
that.onFulfilledCallbacks.forEach(item => item(that.value));
}
}
function reject(reason) {
if(that.status === PENDING){
that.status = REJECTED;
that.status = REJECTED;
that.reason = reason;
that.onRejectedCallbacks.forEach(item => item(that.reason));
}
}
try{
executor(resolve, reject);
}catch(e){
reject(e);
}
}
MyPromise.prototype.then = function(onFulfilled, onRejected){
if(this.status === PENDING){
this.onFulfilledCallbacks.push(onFulfilled);
this.onRejectedCallbacks.push(onRejected);
}
return this;
}
TODO 待完善!