apply与bind实现

  1. apply
   /*
    允许使用es6
    */
    // Function.prototype.apply2 = function (context, args) {
    //   let fun_name = Symbol()
    //   context.fun_name = this
    //   let value = context.fun_name(...args)
    //   delete context.fun_name
    //   return value
    // }
    /*
    不允许允许使用es6
    */
    Function.prototype.apply2 = function (context, args) {
      //手动封装symbol
      function mySymbol(obj) {
        let fun_name = Math.random() + '' + Date.now()
        if (context.fun_name) {
          return mySymbol()
        }
        return fun_name
      }
      let fun_name = mySymbol()
      context.fun_name = this
      let arr = []
      for (let i = 0; i < args.length; i++) {
        arr.push(`args[${i}]`)
      }
      let value = eval('context.fun_name(' + arr.join(',') + ')')
      delete context.fun_name
      return value
    }
    function helloWorld(a, b, c) {
      console.log(a, b, c)
      console.log('helloWorld!', a + b + c)
      return a + b + c
    }
    let obj = {}
    helloWorld.apply2(obj, [1, 2, 3])

2 . bind

 Function.prototype.bind2 = function (context) {
      let args = Array.from(arguments).slice(1)
      let _this = this
      function fbind() {
        return _this.apply(
          //当为new一个对象时 ,this应该指向这个构造体
          this instanceof fbind ? this : context,
          args.concat(arguments)
        )
      }
      // fbind.prototype.__proto__=_this.prototype,让这个对象继承原型上的方法
      fbind.prototype = Object.create(_this.prototype)
      return fbind
    }
    let Cat = function (color, age) {
      this.color = color
      this.age = age
      console.log(this.color, this.age)
    }
    Cat.prototype.helloWorld = function (a, b, c) {
      console.log(this)
      console.log(a, b, c)
      console.log('helloWorld!', a + b + c)
      return a + b + c
    }
    //bind为js原生的方法
    let obj = {}
    let cat1 = Cat.bind(obj, 'red', 3)
    let ca1 = new cat1()
    ca1.helloWorld(1, 2, 3)
    //bind2为实现的方法
    let cat2 = Cat.bind2(obj, 'red', 3)
    let ca2 = new cat2()
    ca2.helloWorld(4, 5, 6)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值