
本文共 2213 字,大约阅读时间需要 7 分钟。
封装自己的JavaScript数组原生方法]
密封自己封装的forEach方法 function myForEach(func, obj) { const len = this.length; const _this = arguments[1] ? arguments[1] : window; for (let i = 0; i < len; i++) { func.call(_this, this[i], i, this); } }
密封自己的filter方法 function myFilter(func, obj) { const len = this.length; const arr = []; const _this = arguments[1] || window; for (let i = 0; i < len; i++) { if (func.call(_this, this[i], i, this)) { arr.push(this[i]); } } return arr; }
实现数组的map方法 function myMap(func) { const arr = []; const len = this.length; const _this = arguments[1] || window; for (let i = 0; i < len; i++) { arr.push(func.call(_this, this[i], i, this)); } return arr; }
实现数组的every方法 function myEvery(func) { let flag = true; const len = this.length; const _this = arguments[1] || window; for (let i = 0; i < len; i++) { if (func.apply(_this, [this[i], i, this]) === false) { flag = false; break; } } return flag; }
实现数组的reduce方法 function myReduce(func, initialValue) { const len = this.length; let nextValue; let i;
if (!initialValue) { nextValue = this[0]; i = 1; } else { nextValue = initialValue; i = 0; }
for (; i < len; i++) { nextValue = func(nextValue, this[i], i, this); } return nextValue; }
实现Function对象的apply方法 Function.prototype myApply = function() { const ctx = arguments[0] || window; const fn = this;
if (arguments.length === 1) { const result = ctx(fn); delete ctx.fn; return result; }
const result = ctx.fn(...arguments.slice(1)); delete ctx.fn; return result; }
实现Function对象的call方法 Function myCall = function() { const ctx = arguments[0] || window; const fn = this;
let result; const args = Array.from(arguments, (value, index) => value);
result = fn(...args); delete ctx.fn; return result; }
实现Function对象的bind方法 Function myBind = function(target) { const self = this; const _target = target ? target : window;
const originalContext = (self instanceof myBind) ? self : _target; const boundFunction = function(...args) { return originalContext.apply(self, args); };
// 处理原函数的上下文和私有变量 boundFunction.prototype = Object.create(self.prototype); boundFunction.prototype.self = self; boundFunction.prototype._target = _target;
return boundFunction; }
请注意:以上代码示例仅用于展示技术实现,实际应用中建议遵循规范,避免直接在生产环境中直接使用这些自定义方法与原型。
发表评论
最新留言
关于作者
