zoukankan      html  css  js  c++  java
  • js 模拟call、apply、bind实现

    call和apply的作用:

    就是"借用"其他的函数,完成事情,第一个参数都是“借用”的主体。

    1、模拟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
    }

    2、模拟apply实现

    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
    }

    3、模拟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))
      }
    }

     

  • 相关阅读:
    算法题-数组算法题
    Linux-shell脚本的调试和追踪
    Linux-循环loop
    Linux-条件判断式
    Linux-第一行#!/bin/bash的含义
    Linux-排序命令:sort、wc、uniq
    Linux-选取命令:cut grep
    Linux-shell变量
    Linux-重定向、追加、tee
    Linux三剑客-sed编辑文本
  • 原文地址:https://www.cnblogs.com/mengfangui/p/10502962.html
Copyright © 2011-2022 走看看