new
- 創(chuàng)建一個空的簡單JavaScript對象(即{});
- 鏈接該對象(即設(shè)置該對象的構(gòu)造函數(shù))到另一個對象 办绝;
- 將創(chuàng)建的對象作為this的上下文 伊约;
- 如果該函數(shù)沒有返回對象,則返回this孕蝉。
function myNew(fn, ...args) {
const obj = {};
obj.__proto__ = fn.prototype;
const res = fn.call(obj, ...args);
return typeof res === "object" ? res : obj;
}
call
- 將函數(shù)設(shè)置為對象屬性
- 執(zhí)行函數(shù)
- 刪除對象的這個屬性
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實現(xiàn)
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() {
// 有定時器了屡律,在規(guī)定時間內(nèi)再觸發(fā)就要清除前面的定時,重新計時
if(timer){
clearTimeout(timer)
}
// 重新計時
timer = setTimeout(fn, (wait));
}
}
節(jié)流throttle
function throttle(fn, wait,...args){
var pre = Date.now();
return function() {
// 函數(shù)可能會有入?yún)? var context = this
var now = Date.now()
if(now - pre >= wait){
// 將執(zhí)行函數(shù)的this指向當(dāng)前作用域
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的初始狀態(tài)為pending
self.success = undefined; //保存成功回調(diào)傳遞的值
self.error = undefined; //保留失敗回調(diào)傳遞的值
self.onSuccessCallbacks = []; //存放成功的回調(diào)
self.onErrorCallbacks = []; //存放失敗的回調(diào)
function resolve(success) {
if (self.status === "pending") {
self.status = "resolved"; //成功函數(shù)將其狀態(tài)修改為resolved
self.success = success; //將成功的值保存起來
self.onSuccessCallbacks.forEach((element) => {
element();
});
}
}
function reject(error) {
if (self.status === "pending") {
self.status = "rejected"; //失敗函數(shù)將其狀態(tài)修改為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函數(shù)保留的成功值傳遞作為參數(shù)
resolvePromise(promiseAgain, x, resolve, reject);
} catch (e) {
reject(e);
}
});
self.onErrorCallbacks.push(() => {
try {
let x = onRejected(self.error); //將rejected函數(shù)保留的失敗值傳遞作為參數(shù)
resolvePromise(promiseAgain, x, resolve, reject);
} catch (e) {
reject(e);
}
});
}
if (self.status === "resolved") {
try {
let x = onResolved(self.success); //將resolve函數(shù)保留的成功值傳遞作為參數(shù)
resolvePromise(promiseAgain, x, resolve, reject);
} catch (e) {
reject(e);
}
}
if (self.status === "rejected") {
try {
let x = onResolved(self.error); //將rejected函數(shù)保留的失敗值傳遞作為參數(shù)
resolvePromise(promiseAgain, x, resolve, reject);
} catch (e) {
reject(e);
}
}
});
return promiseAgain;
};
function resolvePromise(promiseAgain, x, resolve, reject) {
if (promiseAgain === x) {
return reject(new TypeError("循環(huán)調(diào)用"));
}
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("第一次調(diào)用", res);
return res;
},
(err) => {
console.log("error", err);
}
).then(
(res) => {
console.log("第二次調(diào)用", res);
return res;
},
(err) => {
console.log("err", err);
}
).then(
(res) => {
console.log("第三次調(diào)用", res);
return res;
},
(err) => {
console.log("err", err);
}
);
console.log("首先執(zhí)行");
Promise.all
function myPromiseAll(promises){
return new Promise((resolve,reject) =>{
if(!Array.isArray(promises)){
throw new TypeError('promises必須是數(shù)組');
}
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');
});