bind & ArrayFilter

170 阅读1分钟

bind

Function.prototype.myBind  = function(targetThis,...restArgs){
    targetThis[this.name] = this;
    return (...args)=>{
    	return targetThis[this.name](...restArgs,...args);
    }
}

ArrayFilter

Array.prototype.filter = Array.prototype.filter || function(predicate,context=null){
	if(typeof predicate !== 'function'){
    	throw new TypeError('first argument muse be a function!');
    }
    const target = [];
    this.forEach((element,idx)=>{
    	predicate(element,idx,this) ? target.push(element) : null;
    });
    return target;
}
//usage
var a = [1, 2, 3];
var b = a.filter(function (value, idx, list) {
  return value <= 2;
});
console.log(b); // [1,2]