小冯的手写一个系列1(new/call/apply/bind/instanceof/reduce)

  1. 不加注释了,大家自己阅读,都掌握了的请移步大厂。

  2. 手写一个new

    function _new(fn, ...args) {
          
          
        const obj = Object.create(fn.prototype)
        const ret = fn.apply(obj, args)
        return ret instanceof Object ? ret : obj
    }
    
  3. 手写一个call

    Function.prototype._call = function (context, ...args) {
          
          
        let context = context || window
        context.fn = this
        const res = context.fn(...args)
        delete context.fn
        return res
    }
    
  4. 手写一个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
    }
    
  5. 手写一个bind

    Function.prototype._bind = function (context, ...args) {
          
          
        let self = this
        return function (...rest) {
          
          
            return self.apply(context, [...rest, ...args])
        }
    }
    
  6. 手写一个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__
        }
    }
    
  7. 手写一个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
    }
    

猜你喜欢

转载自blog.csdn.net/weixin_38653273/article/details/115263696