new
- 创建一个空的简单JavaScript对象(即{});
- 链接该对象(即设置该对象的构造函数)到另一个对象 ;
- 将创建的对象作为this的上下文 ;
- 如果该函数没有返回对象,则返回this。
function myNew(fn, ...args) {
const obj = {};
obj.__proto__ = fn.prototype;
const res = fn.call(obj, ...args);
return typeof res === "object" ? res : obj;
}
call
- 将函数设置为对象属性
- 执行函数
- 删除对象的这个属性
Function.prototype.call = function(context,...args){
let cxt = context || window;
cxt.fn = this;
args = args ? args : [];
let res = cxt.fn(...args);
delete cxt.fn;
return res;
}
apply
//类似call实现
Function.prototype.apply = function(context,arr){
let cxt = context || window;
cxt.fn = this;
let res;
if(!arr){
res = cxt.fn();
}else{
res = cxt.fn(...arr)
}
delete cxt.fn;
return res;
}
bind
Function.prototype.bind = function(context,...args){
const fn = this;
args = args ? args : [];
return function newFn(...newFnArgs){
if(this instanceof newFn){
return new fn(...args,...newFnArgs);
}
return fn.apply(context, [...args,...newFnArgs]);
}
}
防抖debounce
function debounce(fn, wait){
var timer;
return function() {
// 有定时器了,在规定时间内再触发就要清除前面的定时,重新计时
if(timer){
clearTimeout(timer)
}
// 重新计时
timer = setTimeout(fn, (wait));
}
}
节流throttle
function throttle(fn, wait,...args){
var pre = Date.now();
return function() {
// 函数可能会有入参
var context = this
var now = Date.now()
if(now - pre >= wait){
// 将执行函数的this指向当前作用域
fn.apply(context,args)
pre = Date.now()
}
}
}
深拷贝deepClone
function deepClone(obj){
if(!obj){
return null;
}
if(obj instanceof RegExp){
return new RegExp(obj);
}
if(obj instanceof Date){
return new Date(obj);
}
let objClone = Array.isArray(obj) ? [] : {};
for(let key in obj){
if(obj.hasOwnProperty(key)){
if(obj[key] && typeof obj[key] === 'object'){
objClone[key] = deepClone(obj[key]);
}else{
objClone[key] = obj[key];
}
}
}
return objClone;
}
var dog = {
name: {
chineseName:"狗"
}
}
var newDog = deepClone(dog)
newDog.name.chineseName = "新狗"
console.log("newDog",newDog)//{ name: { chineseName:"新狗"}}
console.log("dog",dog)//{ name: { chineseName:"狗"}}
promise
function Promise(executor) {
let self = this; //保留this,防止后面方法中this指向不明
self.status = "pending"; //promise的初始状态为pending
self.success = undefined; //保存成功回调传递的值
self.error = undefined; //保留失败回调传递的值
self.onSuccessCallbacks = []; //存放成功的回调
self.onErrorCallbacks = []; //存放失败的回调
function resolve(success) {
if (self.status === "pending") {
self.status = "resolved"; //成功函数将其状态修改为resolved
self.success = success; //将成功的值保存起来
self.onSuccessCallbacks.forEach((element) => {
element();
});
}
}
function reject(error) {
if (self.status === "pending") {
self.status = "rejected"; //失败函数将其状态修改为rejected
self.error = error; //将失败的值保存起来
self.onErrorCallbacks.forEach((element) => {
element();
});
}
}
try {
executor(resolve, reject);
} catch (err) {
reject(err);
}
}
Promise.prototype.then = function (onResolved, onRejected) {
onResolved = typeof onResolved == "function" ? onResolved : (val) => val;
onRejected =
typeof onRejected == "function"
? onRejected
: (err) => {
throw err;
};
let self = this;
let promiseAgain = new Promise((resolve, reject) => {
if (self.status === "pending") {
self.onSuccessCallbacks.push(() => {
try {
let x = onResolved(self.success); //将resolve函数保留的成功值传递作为参数
resolvePromise(promiseAgain, x, resolve, reject);
} catch (e) {
reject(e);
}
});
self.onErrorCallbacks.push(() => {
try {
let x = onRejected(self.error); //将rejected函数保留的失败值传递作为参数
resolvePromise(promiseAgain, x, resolve, reject);
} catch (e) {
reject(e);
}
});
}
if (self.status === "resolved") {
try {
let x = onResolved(self.success); //将resolve函数保留的成功值传递作为参数
resolvePromise(promiseAgain, x, resolve, reject);
} catch (e) {
reject(e);
}
}
if (self.status === "rejected") {
try {
let x = onResolved(self.error); //将rejected函数保留的失败值传递作为参数
resolvePromise(promiseAgain, x, resolve, reject);
} catch (e) {
reject(e);
}
}
});
return promiseAgain;
};
function resolvePromise(promiseAgain, x, resolve, reject) {
if (promiseAgain === x) {
return reject(new TypeError("循环调用"));
}
if (x !== null && (typeof x === "object" || typeof x === "function")) {
try {
let then = x.then;
if (typeof then === "function") {
then.call(
x,
(y) => {
resolvePromise(promiseAgain, y, resolve, reject);
},
(e) => {
reject(e);
}
);
} else {
resolve(x);
}
} catch (error) {
reject(error);
}
} else {
resolve(x);
}
}
let promise = new Promise((resolve, reject) => {
setTimeout(function () {
resolve("success data");
}, 0);
// throw new Error("抛出一个错误");
});
promise.then(
(res) => {
console.log("第一次调用", res);
return res;
},
(err) => {
console.log("error", err);
}
).then(
(res) => {
console.log("第二次调用", res);
return res;
},
(err) => {
console.log("err", err);
}
).then(
(res) => {
console.log("第三次调用", res);
return res;
},
(err) => {
console.log("err", err);
}
);
console.log("首先执行");
Promise.all
function myPromiseAll(promises){
return new Promise((resolve,reject) =>{
if(!Array.isArray(promises)){
throw new TypeError('promises必须是数组');
}
let result = [];
let count = 0;
promises.forEach((promise,index) =>{
promise.then((res) =>{
result[index] = res;
count++;
if(count === promises.length){
resolve(result);
}
},(err) =>{
reject(err);
})
})
})
}
//验证
let p1 = Promise.resolve(1),p2 = Promise.resolve(2),p3 = Promise.resolve(3);
myPromiseAll([p1,p2,p3]).then((res) =>{
console.log(res,'res');
},(err) =>{
console.log(err,'err');
});