当前位置: 首页 > Web前端 > vue.js

call方法和apply方法的实现

时间:2023-03-31 18:36:45 vue.js

在阅读本文之前,你应该先了解es6中call方法和apply方法的用法以及展开运算符...的使用。1.call当函数调用call方法时,call接收的一个参数将作为调用函数的this,调用函数本身的参数从调用中的第二个形参开始一个一个接收。call的用法就不详细介绍了,下面是我的实现方法:Function.prototype.myCall=function(thisValue,...args){thisValue.fn=this;让res=thisValue.fn(...args);删除thisValue.fn;returnres}constobj={type:'obj'}functiongetName(){returnthis.type}console.log(getName());}console.log(getName.call(obj));控制台.log(getName.myCall(obj));myCall中传入了一个obj,在getName中会使用obj作为this来执行getName中的代码。首先将调用函数getName赋给obj的一个属性,thisValue.fn=this;,然后通过obj.fn(...args)改变this的指向,然后删除添加到obj的属性,最后返回函数执行结果。2、applyapply和call的唯一区别是call是一个一个接收原始参数,而apply是用一个数组来接收。fn.call(obj,param1,param2..)fn.apply(obj,[pram1,param2,..])apply的实现和call很像,就不解释了:Function.prototype.myApply=function(thisValue,args){thisValue.fn=this;//判断第二个参数是否有值(长度不为0的数组)letres=args&&args.length?thisValue.fn(...args):thisValue.fn()deletethisValue.fn;返回资源}