functionrender(template, data){const pattern =/\{\{\s*(\w+)\s*\}\}/;if(pattern.test(template)){const name = pattern.exec(template)[1];
template = template.replace(pattern, data[name]);returnrender(template, data);}return template;}let template ='我是{{name}},职业{{job}},工资{{salary}}';let person ={name:'阿巴',job:'前端',salary:30000};
console.log(render(template, person));// 我是阿巴,职业前端,工资30000
三、手写new方法
functionmyNew(Fn,...args){let newObj ={};if(Fn.prototype){
newObj.__proto__ =Fn.prototype;}let result =Fn.apply(newObj, args);// 如果new的结果是对象则返回这个对象,否则直接返回这个新创建的对象if((typeof result ==='object'&& result !==null)||typeof result ==='function'){return result;}return newObj;}
四、手写Object.create
// proto 可以是object 或者function
Object.myCreate=function(proto, defineProperties){if((typeof proto ==='object'&& proto !==null)||typeof proto ==='function'){let obj ={};// obj.__proto__ = proto;
Object.setPrototypeOf(obj, proto);
Object.defineProperty(obj, defineProperties);return obj;}else{thrownewTypeError('类型错误');}}
五、手写EventBus
classEventBus{constructor(){this.listeners ={};}on(event, listener){if(!this.listeners[event]){this.listeners[event]=[];}this.listeners[event].push(listener);}off(event, listener){if(this.listeners[event]){const index =this.listeners[event].indexOf(listener);if(index >-1){this.listeners[event].splice(index,1);}}}emit(event,...args){if(this.listeners[event]){this.listeners[event].forEach(listener=>listener(...args));}}}const bus =newEventBus();
bus.on('login',function(name){
console.log('12313', name);})
bus.on('login',function(name){
console.log('1231223', name);})
bus.emit('login',1222313);
六、手写forEach
Array.prototype._forEach=function(callbackFn, ins){if(typeof callbackFn !=='function'){thrownewTypeError(callbackFn +'is not function');}const arr =this;const len = arr.length;for(let i =0; i < len; i++){callbackFn.call(ins, arr[i], i, arr);}}
七、手写map
Array.prototype._map=function(callbackFn, ins){if(typeof callbackFn !=='function'){thrownewTypeError(callbackFn +'is not function');}const arr =this;const len = arr.length;const result =newArray(len);for(let i =0; i < len; i++){
result[i]=callbackFn.call(ins, arr[i], i, arr);}// 返回map结果return result;};const sss =[1,2,3,4]._map(function(item){return item * item;});
console.log(sss);
八、手写filter
// Array.filterArray.prototype._filter=function(callbackFn, ins){if(typeof callbackFn !=='function'){thrownewTypeError(`${callbackFn} is not a function`);}const arr =this;const len = arr.length;const temp =[];for(let i =0; i < len; i++){const result =callbackFn.call(ins, arr[i], i, arr);// push方法 返回新数组的长度
result && temp.push(arr[i]);}return temp;}const result =[1,2,3,4]._filter(item=> item >2);
console.log('result', result);
Function.prototype._call=function(target,...args){if(typeofthis!=='function'){throwError('');}
target = target || window;let key =Symbol('fn');
target[key]=this;const res = target[key](...args);delete target[key];return res;}constB={name:'B',say(prefix, age){
console.log(`${prefix},my name is ${this.name},i am ${age} year old`)}}constA={name:'小A'}
console.log(B.say._call(A,'prefix',18));
十一、手写bind
Function.prototype._bind=function(target,...args){if(typeofthis!=='function'){thrownewError('type Error');}
context = target || window;const _this =this;returnfunctionfn(...innerArgs){if(thisinstanceoffn){returnnew_this(...args,...innerArgs);}else{return_this.apply(context,[...args,...innerArgs]);}}}functionfoo(x, y, z){this.name ="张三";
console.log(this.num, x + y + z);
console.log(this.name);}var obj ={num:666}var foo2 = foo._bind(obj,1,2,3);
console.log(newfoo2);
functionfn1(x){return x +1;}functionfn2(x){return x +2;}functionfn3(x){return x +3;}functionfn4(x){return x+4;}functioncompose(...fn){if(!fn.length){returnv=> v;}if(fn.length ===1){return fn[0];}return fn.reduce((pre, curr)=>(...args)=>{returnpre(curr(...args));})}const a =compose(fn1, fn2, fn3, fn4);
console.log(a(3))
十六、手写柯里化
functiontoCurry(func,...args){let len = func.length;returnfunction(...params){let _args =[...args,...params];if(_args.length < len){returntoCurry(func,..._args);}else{returnfunc.apply(this, _args);}}}constadd=function(a, b, c){return a + b + c;}const a =toCurry(add,1,2);
console.log(a(4))
十七、手写防抖函数
<html><body><div><label for="input1">labe1</label><input id="input1" oninput=input(value)/><label for="input2">labe2</label><input id="input2"/><button id="button">click</button></div></body><script>constdebounce=function(fn, wait){let time;returnfunction(...args){if(time){clearTimeout(time);}
time =setTimeout(()=>{fn.apply(this, args);}, wait);}}// 立即执行防抖函数constdebounce2=function(fn, wait, immediate){let time;returnfunction(...args){const _this =this;if(time){clearTimeout(time);}if(immediate){const action =!time;
time =setTimeout(()=>{fn.apply(_this, args);
time =null;}, wait);if(action){fn.apply(_this, args);}}else{
time =setTimeout(()=>{fn.apply(_this, args);}, wait);}}}// 节流函数立即执行版functionthrottle(fn, wait){let flag =true;let timer =null;returnfunction(...args){if(flag){fn.apply(this, args);
flag =false;
timer =setTimeout(()=>{
flag =true;}, wait);}}}functionthrottle2(fn, wait){let time =null;returnfunction(){if(time){return;}
time =setTimeout(()=>{fn.apply(this, arguments);
time =null;}, wait);}}const input =debounce(function(v){
console.log('v', v);},300);const input2 =debounce2(function(args){
console.log('args------', args);},300,true);const inputDom = document.getElementById('input2');
inputDom.addEventListener('input',event=>input2(event))const button = document.getElementById('button');
button.addEventListener('click',e=>{input2(e)})</script></html>