手写 call 函数
考察点:
1)不能借助bind,apply函数
2)call方法写到什么位置?
3)函数接收哪些參数?剩余参数 …args
4)this如果传递的是数字 1,那this指向的是什么,如果传道的是null,undefined
参数归一化告数有很多种情况,全部合并成一种情况、将参数鞋化成对象.
GlobalThis 全局对象
Object工具函数将普通类型转化成对象.
5)call 函数内怎么执行函数?this即函数本身
6)在传入的this上添加一个属性(唯一属性)
Function.prototype.myCall = function myCall(ctx, ...params) {
ctx = ctx === null || ctx === undefined ? globalThis : Object(ctx)
const fn = Symbol()
Object.defineProperty(ctx, fn, {
value: this,
enumerable: false, // 默认值,不可枚举
configurable: true
});
const res = ctx[fn](...params)
delete ctx.fn
console.log(ctx.fn)
return res
}
function testCall(...params){
console.log(this)
console.log(params)
return 'success'
}
testCall.myCall(this, 1,2,3)
手写 Promise.all
考察点:
1)传入的各数不定是数组,而是一个可迭代对象
2)如何得到一个可选代对象的长度 用 for...of
数组长厦、set或者Map 的长度用 size
3)如果传入的不是 Promise 对象需要自装成 Promise 对象,使用 Promise.resolve 函数包装传入的每一个元素,将其包装成 Promise
4)结果怎么按顺序返回,涉及到局部变量,以及 for 循环的异步函数中得到最后一次 for 循环同步执行的结果等知识
5)如何判定全部执行结束?
6)如果有一个执行失败怎么办?
// 手写 promise.all
Promise.allPromise = function all(promiseList){
let resolvePromise, rejectPromise
const newPromise = new Promise((resolve, reject)=>{
resolvePromise = resolve
rejectPromise = reject
})
let i = 0, result = [], fullFilled = 0
for(const item of promiseList){
const index = i;
i++
Promise.resolve(item).then((res)=>{
fullFilled++
result[index] = res
if(fullFilled === i){
resolvePromise(result)
}
}, rejectPromise)
}
if(i === 0 ){
resolvePromise([])
}
return newPromise
}
function promise1(){
return new Promise(res=>res(4))
}
function promise2(){
return Promise.resolve(2)
}
Promise.allPromise([promise1(), promise2()]).then((res)=>{
console.log(res)
})