zoukankan      html  css  js  c++  java
  • call, apply, bind 区别

    #call, apply, bind 区别及模拟实现call apply bind

          三者都可以用来改变this的指向,但是在用法上略有不同

     首先说一下call和apply的区别

      call和apply都是第一个参数是this的指向  ,只是传参的方式不同

      call是 第二个以及第三依次类推都是当前函数的参数,每个参数用逗号相隔开

      而apply则是将所有的参数以数组的形式来传递的

     call(window,参数1,参数1,参数3)

    call和apply与bind的区别

    call和apply相当于立即执行函数,使用时直接调用,而bind则类似于函数,使用时需要加()调用

    同时bind传参方式与call相同,参数都是一个一个传递的

    模拟实现call  

    代码

    Function.prototype.myCall = function (context) {
      var context = context || window
      // 给 context 添加一个属性
      // getValue.call(a, 'yck', '24') => a.fn = getValue
      context.fn = this
      // 将 context 后面的参数取出来
      var args = [...arguments].slice(1)
      // getValue.call(a, 'yck', '24') => a.fn('yck', '24')
      var result = context.fn(...args)
      // 删除 fn
      delete context.fn
      return result
    }

    模拟实现apply   方式与call相似只是传参方式不同

     代码

    Function.prototype.myApply = function (context) {
      var context = context || window
      context.fn = this
    
      var result
      // 需要判断是否存储第二个参数
      // 如果存在,就将第二个参数展开
      if (arguments[1]) {
        result = context.fn(...arguments[1])
      } else {
        result = context.fn()
      }
    
      delete context.fn
      return result
    }

    模拟实现bind

    代码

    Function.prototype.myBind = function (context) {
      if (typeof this !== 'function') {
        throw new TypeError('Error')
      }
      var _this = this
      var args = [...arguments].slice(1)
      // 返回一个函数
      return function F() {
        // 因为返回了一个函数,我们可以 new F(),所以需要判断
        if (this instanceof F) {
          return new _this(...args, ...arguments)
        }
        return _this.apply(context, args.concat(...arguments))
      }
    }

    如果本文对您有帮助,请抬抬您的小手,点下右下角的推荐, ^-^,当然如果看了这篇博客对您有帮助是我最开心的事,毕竟赠人玫瑰,手有余香, ^-^,如果这篇博客没有帮助到您,那就只能说一声抱歉啦

  • 相关阅读:
    window安装maven仓库
    python代码实现将json中所有字段四舍五入保留n位小数
    Centos搭建Git服务器,添加用户名密码实现多用户管理
    python的测试工具大全
    TypeError: cannot serialize '_io.BufferedReader' object 问题记录
    mysql数据库无法插入中文字符
    jquery的相关用法
    js相关用法
    二分法+装饰器(带返回值,无敌参数,批量执行/取消装饰器)
    网络编程三 Socket
  • 原文地址:https://www.cnblogs.com/katydids/p/9920472.html
Copyright © 2011-2022 走看看