Function.prototype.bind=function(...args){if(typeofthis!=='function') {thrownewError('Function.prototype.bind - what to be bound is not a function'); }constfn=this;constcontext= args[0] || window;constarg=args.slice(1);constreturnFun=function(...innerArgs) {constnewContext= context;if(thisinstanceofreturnFun) {// it means, function is called as Constructor newContext =this; }returnfn.apply( newContext, [].concat(arg, innerArgs) ); }functionNOOP() {}NOOP.prototype=this.prototype;returnFun.prototype=newNOOP();return returnFun;}
functionobjectFactory(Constructor,...args) {constobj= {};constret=Constructor.apply(obj,args)obj.__proto__=Constructor.prototype;returntypeof ret ==='object'? ret : obj;}
5. clone
深拷贝浅拷贝
注意:
深拷贝的情况,如果属性值是对象,则进行递归
functionclone(obj, isDeep) {if(typeof obj !=='object') {thrownewError('clone: the arguments[0] should be an object'); }constnewObj= obj instanceofArray? [] : {};Object.keys(obj).forEach(key => {if(isDeep &&typeof obj[key] ==='object') { newObj[key] =clone(obj[key]) } else { newObj[key] = obj[key] } })return newObj;}