防抖节流
function debounce(fn, delay) {
let timer = null;
return function (...args) {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
fn.apply(this, args);
}, delay);
};
}
function debounce(fn, time, triggleNow) {
let timer = null;
return function () {
let _self = this,
args = arguments,
result = null;
if (timer) {
clearTimeout(timer);
}
if (triggleNow) {
const exec = !timer;
timer = setTimeout(() => {
timer = null;
}, time);
if (exec) {
result = fn.apply(_self, args);
}
} else {
timer = setTimeout(() => {
result = fn.apply(_self, args);
}, time);
}
return result;
}
}
function throttle(fn, delay) {
let timer = null;
return function (...args) {
if (!timer) {
timer = setTimeout(() => {
timer = null;
fn.apply(this, args);
}, delay);
}
};
}
function throttle (fn, delay, needLast) {
let timer = null,
beginTime = new Date().getTime();
return function () {
let _self = this,
args = arguments,
curTime = new Date().getTime(),
result = null;
clearTimeout(timer)
if (curTime - beginTime >= delay) {
result = fn.apply(_self, args);
beginTime = curTime;
} else {
if (needLast) {
timer = setTimeout(() => {
result = fn.apply(_self, args);
}, delay);
}
}
return result
}
}
new
function Person(name, age) {
this.name = name;
this.age = age;
}
function create(ctor, ...args) {
if (typeof ctor !== 'function') {
throw 'constructor error'
}
let newObj = {};
newObj._proto_ = ctor.prototype;
ctor.call(newObj, ...args);
return newObj;
}
let obj = create(Person, 'jzy', 18);
console.log('createObj', obj);
let obj2 = new Person('jzy', 18);
console.log('newObj', obj2);
call 、 apply

Function.prototype.myCall = function (context, ...args) {
context = context ? Object(context) : window;
const key = Symbol();
context[key] = this;
const result = context[key](...args);
delete context[key];
return result;
};
Function.prototype.myApply = function (context, args) {
context = context ? Object(context) : window;
const key = Symbol();
context[key] = this;
const result = args ? context[key](...args) : context[key]();
delete context[key];
return result;
};
bind

Function.prototype.myBind = function (context, ...outArgs) {
context = context || {};
let that = this;
let fn = function (...innerArgs) {
if (this instanceof fn) {
return that.call(this, ...outArgs, ...innerArgs);
} else {
return that.call(context, ...outArgs, ...innerArgs);
}
};
fn.prototype = this.prototype;
return fn1;
};
深拷贝
function deepClone(obj, map = new WeakMap()) {
let cloneObj;
if (typeof obj !== "object") return obj;
if (map.has(obj)) return map.get(obj);
cloneObj = new obj.constructor();
map.set(obj, cloneObj);
for (let key in obj) {
cloneObj[key] = deepClone(obj[key]);
}
return cloneObj;
}