A series of Xiaofeng's handwriting 1 (new/call/apply/bind/instanceof/reduce)

  1. No comments, please read it yourself, please move to Dachang if you have mastered it.

  2. Hand write a new :

    function _new(fn, ...args) {
          
          
        const obj = Object.create(fn.prototype)
        const ret = fn.apply(obj, args)
        return ret instanceof Object ? ret : obj
    }
    
  3. Write a call by hand :

    Function.prototype._call = function (context, ...args) {
          
          
        let context = context || window
        context.fn = this
        const res = context.fn(...args)
        delete context.fn
        return res
    }
    
  4. Write an apply by hand :

    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. Write a bind by hand :

    Function.prototype._bind = function (context, ...args) {
          
          
        let self = this
        return function (...rest) {
          
          
            return self.apply(context, [...rest, ...args])
        }
    }
    
  6. Handwriting an 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. Write a reduce by hand :

    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
    }
    

Guess you like

Origin blog.csdn.net/weixin_38653273/article/details/115263696