前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >探究call、bind、apply知识点

探究call、bind、apply知识点

作者头像
w候人兮猗
发布2020-07-01 15:28:09
3420
发布2020-07-01 15:28:09
举报

Contents

call、bind、apply知识点

一、食用方式
  • apply
代码语言:javascript
复制
function.apply(obj, [param1,params2,...])
// obj:要绑定的this
// 第二个参数:类数组或数组,作为function的参数传入
// 立即执行
  • call
代码语言:javascript
复制
function.call(obj, param1, param2, ...)
// obj:要绑定的this
// 第二个参数:函数运行的参数,用逗号隔开
// 立即执行
  • bind
代码语言:javascript
复制
function.bind(obj, param1, param2, ...)
// obj:要绑定的this
// 第二个参数:函数运行的参数,用逗号隔开
// 返回一个函数
二、使用场景

基本理念:借用方法,修改this指向

  • 获取数据类型
代码语言:javascript
复制
const params = 'ahwgs'
const toString = Object.prototype.toString
const type = toString.call(params)
console.log('数据类型',type) // [object String]
  • 类数组借用数组的方法
代码语言:javascript
复制
var arrayLike = {
  0: 'OB',
  1: 'Koro1',
  length: 2
}
Array.prototype.push.call(arrayLike, '添加元素1', '添加元素2');
console.log(arrayLike) // {"0":"OB","1":"Koro1","2":"添加元素1","3":"添加元素2","length":4}

借用数组的push方法,向arrayLikepush新数据

三、手写实现
  • 手写call实现
代码语言:javascript
复制
Function.prototype.myCall = function(context,...arr) {
    if (context === null || context === undefined) {
     // 指定为 null 和 undefined 的 this 值会自动指向全局对象(浏览器中为window)
     context = window
    } else {
     context = Object(context) // 值为原始值(数字,字符串,布尔值)的 this 会指向该原始值的实例对象
    }
    const specialPrototype = Symbol('特殊属性Symbol') // 用于临时储存函数
    context[specialPrototype] = this; // 函数的this指向隐式绑定到context上
    let result = context[specialPrototype](...arr); // 通过隐式绑定执行函数并传递参数
    delete context[specialPrototype]; // 删除上下文对象的属性
    return result; // 返回函数执行结果
 }
  • 手写apply
代码语言:javascript
复制
Function.prototype.myApply = function (context) {
    if (context === null || context === undefined) {
      context = window // 指定为 null 和 undefined 的 this 值会自动指向全局对象(浏览器中为window)
    } else {
      context = Object(context) // 值为原始值(数字,字符串,布尔值)的 this 会指向该原始值的实例对象
    }
    // JavaScript权威指南判断是否为类数组对象
    function isArrayLike(o) {
      if (o &&                                    // o不是null、undefined等
        typeof o === 'object' &&                // o是对象
        isFinite(o.length) &&                   // o.length是有限数值
        o.length >= 0 &&                        // o.length为非负值
        o.length === Math.floor(o.length) &&    // o.length是整数
        o.length < 4294967296)                  // o.length < 2^32
        return true
      else
        return false
    }
    const specialPrototype = Symbol('特殊属性Symbol') // 用于临时储存函数
    context[specialPrototype] = this; // 隐式绑定this指向到context上
    let args = arguments[1]; // 获取参数数组
    let result
    // 处理传进来的第二个参数
    if (args) {
      // 是否传递第二个参数
      if (!Array.isArray(args) && !isArrayLike(args)) {
        throw new TypeError('myApply 第二个参数不为数组并且不为类数组对象抛出错误');
      } else {
        args = Array.from(args) // 转为数组
        result = context[specialPrototype](...args); // 执行函数并展开数组,传递函数参数
      }
    } else {
      result = context[specialPrototype](); // 执行函数
    }
    delete context[specialPrototype]; // 删除上下文对象的属性
    return result; // 返回函数执行结果
};
  • 手写bind
代码语言:javascript
复制
Function.prototype.myBind = function (objThis, ...params) {
    const thisFn = this; // 存储源函数以及上方的params(函数参数)
    // 对返回的函数 secondParams 二次传参
    let fToBind = function (...secondParams) {
        const isNew = this instanceof fToBind // this是否是fToBind的实例 也就是返回的fToBind是否通过new调用
        const context = isNew ? this : Object(objThis) // new调用就绑定到this上,否则就绑定到传入的objThis上
        return thisFn.call(context, ...params, ...secondParams); // 用call调用源函数绑定this的指向并传递参数,返回执行结果
    };
    if (thisFn.prototype) {
        // 复制源函数的prototype给fToBind 一些情况下函数没有prototype,比如箭头函数
        fToBind.prototype = Object.create(thisFn.prototype);
    }
    return fToBind; // 返回拷贝的函数
};
关于
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019年10月23日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • call、bind、apply知识点
    • 一、食用方式
      • 二、使用场景
        • 三、手写实现
          • 关于
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档