手动实现call apply bind

基本使用

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

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

 
  1. function greet(name) {

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

  3. }

  4. var obj = {

  5.  animal: 'cats'

  6. };

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

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

 
  1. function greet(name) {

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

  3. }

  4. var obj = {

  5.  animal: 'cats'

  6. };

  7. 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

猜你喜欢

转载自blog.csdn.net/sinat_17775997/article/details/89052534