call()函数知多少

彻底理解call

        var obj = {
            name: "pig"
        }
        function showName() {
            return this.name;
        }
        console.log(showName.call(obj));

        var name = "pig1";
        var obj = {
            name: "pig2",
            fn: function showName() {
                return this.name;
            }
        }
        console.log(obj.fn());

        // 把当前执行函数的this指向传入的对象obj,等于在对象obj中调用当前函数
        // 创建obj中的假当前函数fn=Symbol(),通过obj[fn] = this将当前函数转给他
        // 执行假函数并返回,返回前删除创建的假函数
        Function.prototype.myCall = function (obj = window, ...args) {
            const fn = Symbol();
            obj[fn] = this;
            const newFunc = obj[fn](...args);
            delete obj[fn];
            return newFunc;
        }

        Function.prototype.myApply = function (target, args) { // 区别就是这里第二个参数直接就是个数组
            target = target || window
            const symbolKey = Symbol()
            target[symbolKey] = this
            const res = target[symbolKey](...args) // args本身是个数组,所以我们需要解构后一个个传入函数中
            delete target[symbolKey] // 执行完借用的函数后,删除掉,留着过年吗?
            return res
        }

# 手动实现call()函数

      // c1.showAge.call(c2, 18);
      // c2就是context,c1里的this给了c2添加的属性fn上,调用c1.showAge就是this.showAge就是context[fn].showAge
      Function.prototype.myCall = function (context = window, ...args) {
        const fn = Symbol(); // 创建一个独一无二的symbol:fn
        context[fn] = this; //将fn作为属性添加到context上
        console.log("this:", this);
        const result = context[fn](...args);
        delete context[fn]; //调用函数后即删除该Symbol属性
        return result;
      };

      function Class1() {
        this.name = "class1";
        this.showName = function () {
          console.log(this.name);
        };
        this.showAge = function (age) {
          console.log(age);
        };
      }
      function Class2() {
        this.name = "class2";
      }
      var c1 = new Class1();
      var c2 = new Class2();
      c1.showName.myCall(c2); // class2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值