带你手动实现call方法,让你收获满满

1.首先,了解call方法的要点

  • 语法:function.call(thisArg, arg1, arg2, ...)
    参数:
    1.thisArg
    在 function 函数运行时使用的 this 值。请注意,this可能不是该方法看到的实际值:如果这个函数处于非严格模式下,则指定为 null 或 undefined 时会自动替换为指向全局对象,原始值会被包装。
    this指向:非严格模式下,指向window。严格模式下,为undefined。
    示例:
	var a = 2;
    var obj = {
        name: 'ha',
        age: 12,
        getSome : function () {
            // 'use strict'; 非严格模式下
            console.log(this); // window
            console.log(a); // 2
        }
    }
    	obj.getSome.call(undefined);
---------------------------------------------------------	
	var a = 2;
	 var obj = {
	        name: 'ha',
	        age: 12,
	        getSome : function () {
	            'use strict'; // 严格模式下
	            console.log(this); // undefined
	            console.log(a); // 2
	        }
	    }

	obj.getSome.call(undefined);
  • 返回值
    使用调用者提供的 this 值和参数调用该函数的返回值。若该方法没有返回值,则返回 undefined。
    手动实现时,还必须将值return出来。

2.手动实现call方法

要点:

  • 返回值
  • 将调用者,转变为this下的一个方法,执行完后,记得删除。
    示例:
const obj = {
	  name: 'ha',
      age: 12,
      getSome : function (a, b) {
          console.log(this);
          return a + b;
      }
  }

  Function.prototype.myCall = function (context = window,...args) {
      var func = this,
      fn = Symbol('fn'); // 确保属性名独一无二
      context[fn] = func; // 这里的转变:调用者(函数)作为context对象的方法
      var res = context[fn](...args);
      delete context[fn]; // 记得将context对象上刚刚新增的func方法删除
      return res;
  }

  const res = obj.getSome.myCall(obj, 1, 2, 3);
  console.log(res);

结果如下:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值