防抖:在事件被触发n秒后再执行回调,如果在这n秒内又被触发,重新计数
function debounce(fn,wait=500){
let timer = null;
return function(...args){
if(timer){
clearTimeout(timer)
}
timer = setTimeout(()=>{
fn.apply(this,args)
}, wait);
}
}
节流:规定时间内只能触发依次函数,如果多次触发只有依次生效
function throttle(fn,wait=500){
let timer = null;
return function(...args){
if(!timer){
timer = setTimeout(() => {
fn.apply(this,args)
timer = null;
}, wait);
}
}
}
深拷贝
function deepClone(obj){
if(typeof obj !== 'object' || obj === null){
return obj
}
let copy = {};
if(obj instanceof Array){
copy = []
}
for(key in obj){
if(obj.hasOwnProperty(key)){
copy[key] = deepClone(obj[key])
}
}
return copy;
}
发布订阅者模式
class EventEmitter{
constructor(max){
this._events = new Map();//存储事件
this.maxListeners = max || 10;
}
addListener(type,fn){
if(typeof fn !== 'function'){
throw new Error('the Second parameter expected a function')
}
const handler = this._events.get(type);
if(!handler){
this._events.set(type,[fn])
}else{
if(handler.length===this.maxListeners){
throw new Error('this length of listeners can not exceed the max')
}
handler.push(fn)
this._events.set(type,handler);
}
}
emit(type,...args){
const handlers = this._events.get(type);
if(!handlers){
throw new Error('you only can emit a listener which you have added')
}else{
handlers.forEach((fn)=>{
fn.apply(this,args);
})
}
}
remove(type,fn){
const handlers = this._events.get(type);
let position = handlers.indexOf(fn);
if(position>-1){
handlers.splice(position,1)
this._events.set(type,handlers);
}
}
}
//测试
let emitEve = new EventEmitter(3);
function test1(){
console.log('测试1')
}
function test2(){
console.log('测试2')
}
function test3(){
console.log('测试3')
}
emitEve.addListener('test',test1)
emitEve.addListener('test',test2)
emitEve.addListener('test',test3)
emitEve.remove('test',test1)
emitEve.emit('test')
模拟Object.create
function create(proto){
function F(){}
F.prototype = proto;
return new F();
}
实现类的继承
function Parent(name,gendar,family){
this.name = name;
this.gendar = gendar;
this.family = family
}
Parent.prototype.sayHello = function(){
console.log('用中国话说hello');
}
function Child(name,gendar,family,like){
Parent(name,gendar,family);
this.like = like;
}
function inherit(parent,son){
son.prototype = Object.create(parent.prototype)
son.prototype.constructor = son;
son.prototype.uber = parent.prototype;
}
inherit(Parent,Child)
实现JSON.stringify
function myJsonStringify(obj){
let type = typeof(obj);
if(type !== 'object'){
if(/number/.test(type)){
return obj;
}else{
return String(obj)
}
}
let json = []
let isArr = Array.isArray(obj);
for( key in obj ){
let v = obj[key];
let type = typeof(obj[key])
if(/string|undefined|function/.test(type)){
v = '"'+v+'"';
}else if(type === "object"){
v = myJsonStringify(v);
}
json.push((isArr?"":'"'+key+'"')+String(v));
}
return (isArr ? "[" : "{") + String(json) + (isArr ? "]" : "}")
}