手写call

首先call的功能:1.调用被绑定函数2.传入this指向,被绑定函数this指向设置内容.3.可以传入参数

第一步:为所有函数设置一个hycall方法,为了知道是哪一个函数调用的hycall,所以用了this(最后一行其实就是隐式绑定,此时this就是调用的函数)。后面的思路就是直接调用这个函数就可以。但是有一些需要考虑的事情。

Function.prototype.hycall = function(thisArg, ...args){
   var fn = this;
   var result = fn(...args); 
   return result;
}

function foo() {
    console.log("foo执行");
}

function sum(num1, num2) {
    console.log("sum执行", num1, num2);
    return num1 + num2;
}
sum.hycall({},1,3);

第二步,考虑this指向。第一步用fn(...args)方法调用需使用的参数例如sum,此时this并没有传入函数this是全局GO。解决这个问题只需要改变fn的调用方式,所以用了加属性的方法。但是多了个属性给他delete掉。

Function.prototype.hycall = function(thisArg, ...args){
   var fn = this;
   thisArg.fn = fn;
   var result = thisArg.fn(...args);
   delete thisArg.fn;
   return result;
}

function foo() {
    console.log("foo执行")
    console.log('this是' + this);
}

function sum(num1, num2) {
    console.log("sum执行", num1, num2)
    return num1 + num2
}

foo.hycall('调用hycall',1,3);

第三步:考虑thisArg传入的是非对象类型,加一行: thisArg = (thisArg !== null && thisArg !== undefined) ? Object(thisArg): window。最终:

Function.prototype.hycall = function(thisArg, ...args){
    var fn = this;
    thisArg = (thisArg !== null && thisArg !== undefined) ? Object(thisArg): window;
    thisArg.fn = fn;
    var result = thisArg.fn(...args);
    delete thisArg.fn;
    return result
 }
 
 function foo() {
     console.log("foo执行")
     console.log('this是' + this);
 }
 
 function sum(num1, num2) {
     console.log("sum执行", num1, num2)
     return num1 + num2
 }
 
 foo.hycall('调用hycall',1,3);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值