-
不加注释了,大家自己阅读,都掌握了的请移步大厂。
-
手写一个new:
function _new(fn, ...args) { const obj = Object.create(fn.prototype) const ret = fn.apply(obj, args) return ret instanceof Object ? ret : obj }
-
手写一个call:
Function.prototype._call = function (context, ...args) { let context = context || window context.fn = this const res = context.fn(...args) delete context.fn return res }
-
手写一个apply:
Function.prototype._apply = function (context, arr) { let context = context || window context.fn = this let res if (!arr) { res = context.fn() } else { res = context.fn(...arr) } delete context.fn return res }
-
手写一个bind:
Function.prototype._bind = function (context, ...args) { let self = this return function (...rest) { return self.apply(context, [...rest, ...args]) } }
-
手写一个instanceof:
function _instanceof(left, right) { let right = right.prototype let left = left.__proto__ while(true){ if (left === null) { return false } if (left === right) { return true } left = left.__proto__ } }
-
手写一个reduce:
Array.prototype._reduce = function(fn, value) { const arr = this let acc = value || array[0] const startIndex = value ? 0 : 1 for (let i = startIndex; i<arr.length; i++) { acc = fn(acc, arr[i], i, arr) } return acc }
小冯的手写一个系列1(new/call/apply/bind/instanceof/reduce)
猜你喜欢
转载自blog.csdn.net/weixin_38653273/article/details/115263696
今日推荐
周排行