手动实现call apply bind

基本使用

都是用来改变一个函数的this指向,用法略有不同。

call:后面的参数为调用函数的参数列表

 
  1. function greet(name) {

  2.  console.log(this.animal,name);

  3. }

  4.  

  5. var obj = {

  6.  animal: 'cats'

  7. };

  8.  

  9. greet.call(obj,'猫咪');

apply:第二个参数为调用函数的参数数组

 
  1. function greet(name) {

  2.  console.log(this.animal,name);

  3. }

  4.  

  5. var obj = {

  6.  animal: 'cats'

  7. };

  8.  

  9. greet.apply(obj,['猫咪']);

bind:当绑定函数被调用时,bind传入的参数会被插入到目标函数的参数列表的开始位置,传递给绑定函数的参数会跟在它们后面。

 
  1. var fun = function (name1,name2){

  2.    console.log(this);

  3.    console.log(name);

  4. }.bind({a:1},"name1");

  5.    fun("name2");

手动实现

  1. context 为可选参数,如果不传的话默认上下文为 window;

  2. context 创建一个 Symbol 属性,调用后即删除,不会影响context

 
  1.    Function.prototype.myCall = function (context) {

  2.      if (typeof this !== 'function') {

  3.        return undefined; // 用于防止 Function.prototype.myCall() 直接调用

  4.      }

  5.      context = context || window;

  6.      const fn = Symbol();

  7.      context[fn] = this;

  8.      const args = [...arguments].slice(1);

  9.      const result = context[fn](...args);

  10.      delete context[fn];

  11.      return result;

  12.    }

apply实现类似call,参数为数组

 
  1.    Function.prototype.myApply = function (context) {

  2.      if (typeof this !== 'function') {

  3.        return undefined; // 用于防止 Function.prototype.myCall() 直接调用

  4.      }

  5.      context = context || window;

  6.      const fn = Symbol();

  7.      context[fn] = this;

  8.      let result;

  9.      if (arguments[1] instanceof Array) {

  10.        result = context[fn](...arguments[1]);

  11.      } else {

  12.        result = context[fn]();

  13.      }

  14.      delete context[fn];

  15.      return result;

  16.    }

1.判断是否为构造函数调用

2.注意参数要插入到目标函数的开始位置

 
  1.    Function.prototype.myBind = function (context) {

  2.      if (typeof this !== 'function') {

  3.        throw new TypeError('Error')

  4.      }

  5.      const _this = this

  6.      const args = [...arguments].slice(1)

  7.      return function F() {

  8.        // 判断是否用于构造函数

  9.        if (this instanceof F) {

  10.          return new _this(...args, ...arguments)

  11.        }

  12.        return _this.apply(context, args.concat(...arguments))

  13.      }

  14.    }

  15. 原文https://mp.weixin.qq.com/s/o7VKwtnV3RMKZ7s2cY14Ig

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值