call apply以及各种数组方法的封装

  Function.prototype.mycall = function() {
      const [context,...args] = arguments
      context = context||window
      context.__proto__.fn = this
      context.fn(...args)
      delete context.__proto__.xxx    //删除xxx函数  避免对象的隐式原型被污染
    }
  // 封装apply函数
    Function.prototype.myapply = function() {
      const [context,...args] = arguments
      context = context||window
      args = args|| []
      context.__proto__.fn = this
      context.fn(...args)
      delete context.__proto__.fn    //删除xxx函数  避免对象的隐式原型被污染
    }

  

// 封装push方法
    Function.prototype.mypush = function(n) {
      this[this.length] = n
      return this.length
    }

  

   // js生成对象的方法
    // 1.var obj = {} 该对象的隐式原型指向Object.prototype
    // 2.var obj = new Fn() 该对象的隐式原型指向Fn.prototype
    // 3.var obj = Object.create(参数对象) 该对象的隐式原型指向参数对象
// 模拟new
    function myNew() {
      let [Fn, ...args] = arguments
      // let obj = {}
      // obj.__proto__ = Fn.prototype    //把obj的隐式原型指向Fn的显式原型
      let obj = Object.create(Fn.prototype)
      Fn.call(obj, ...args)    //借用Fn这个构造函数 给obj添加属性
      return obj
          }

  

// 封装reduce方法
    Array.prototype.myreduce = function(cb,value) {
      if(value||value ==0){
        for(let i =0;i < this.length;i++) {
          value =  cb(value,this[i])
        }
      }else {
        for(let i = 0;i < this.legnth-1;i++){
          value = cb(i===0 ? this[i]: value , this[i+1])
        }
      }
      return value
    }

  

// foreach方法
  Array.prototype.myforeach = function(cb) {
    for(let i = 0 ;i < this.length; i++){
      cb(this[i],i,this)
    }
  }
 Array.prototype.myfilter = function() {
    let arr = []
    for(let i = 0;i < this.length ;i++) {
      if(cb(this[i]),i) {
        arr.push(this[i])
      }
    }
    return arr
  }
 Array.prototype.mymap = function() {
    let arr =[]
    for(let i =0;i < this.length; i++){
      arr.push(cb(this[i],item))
    }
    return arr
  }

猜你喜欢

转载自www.cnblogs.com/388ximengpy/p/12558130.html