当前位置: 首页 > 科技观察

函数里面对this的修改超过72处

时间:2023-03-13 12:22:53 科技观察

在连接你我他的课程中——我们在this中学习了this,最后留下一个问题,如何修改this的方向,今天一起来学习.修改this的点可以通过apply、call、bind这三个函数中的任意一个来实现。这三个函数是谁的方法?我在MDN中找到:这张图说明这三个函数是Function原型的方法,也就是说“每个函数都有三个方法”。定义函数时,函数默认包含这三个方法。下面感受一下在Vue.js中apply、call和bind的使用:;}}}调用应用程序:varhasOwnProperty=Object.prototype.hasOwnProperty;functionhasOwn(obj,key){returnhasOwnProperty.call(obj,key)}绑定应用程序:functionpolyfillBind(fn,ctx){functionboundFn(a){varl=arguments.length;returnl?l>1?fn.apply(ctx,arguments):fn.call(ctx,a):fn.call(ctx)}boundFn._length=fn.length;returnboundFn}functionnativeBind(fn,ctx){returnfn.bind(ctx)}varbind=Function.prototype.bind?nativeBind:polyfillBind;上面的用法大家可能不太理解,下面就放一边一一解答吧。一个新事物的出现,总是有目的的,那么apply、call、bind的出现是为了解决什么问题呢?为什么它们是函数方法?为什么不是其他对象的方法。可以通过apply和call自定义this调用一个函数,比如定义一个全局函数(严格模式):'usestrict';functiongFun(name,age){console.log(this);}这个函数可以在下面5种调用方式,也就是说一个函数F可以通过apply、call、bind来调用,其中“调用时可以指定函数F的执行上下文中的this”:1.直接调用:gFun('suyan',20);//this是undefined2.通过这样调用:this.gFun('suyan',20);//这是window3。通过apply调用,将所有参数组合成一个数组作为apply的参数:gFun.apply(this,['suyan',20]);//thisiswindow4.通过call调用,参数之间用逗号分隔,这是和applycall的区别:gFun.call(this,'suyan',20);//thisiswindow5.通过bind调用会返回原函数的副本,指定this和参数:letbGFun=gFun.bind(this,'suyan',20);bGFun();//thisiswindow下面一起看一些例子:例1,setTimeOut的使用:consttime={second:1,afterOneSecond(){setTimeout(function(){this.second+=1;console.log(this.second);},1000);}};time.afterOneSecond();上面代码执行后,第6行代码打印结果为NaN。在连接你我他的过程中——这个,我们提到过,这个设计的缺点之一就是不能继承。其实可以通过bind修改这个函数:consttime={second:1,afterOneSecond(){setTimeout(this.timeInvoke.bind(this),1000);},timeInvoke(){this.second+=1;console.log(this.second);}};time.afterOneSecond();函数timeInvoke通过bind绑定this,返回一个新的函数,执行结果为2。bind好像有一个“暂存”的功能,暂存当前的this。例2.函数调用constperson={name:'suyan',age:20,showName(pre){returnpre+'-'+this.name;},update(name,age){this.name=name;this.age=age;}};functiongenerateName(fun){letname=fun();console.log('showName=',name);}generateName(person.showName);执行以上代码会报错,因为showName中的this未定义:可以通过bind来“暂存this”:constperson={name:'suyan',age:20,showName(pre){returnpre+'-'+this.name;},update(name,age){this.name=name;this.age=age;}};functiongenerateName(fun){letname=fun();console.log('showName=',name);}//指定this为person对象letbindShowName=person.showName.bind(person,'前端类');generateName(bindShowName);例3,构造函数,通过call调用一个函数,替换this。functionProduct(name,price){this.name=name;this.price=price;}functionFood(name,price){//调用Product函数Product.call(this,name,price);this.catagory='food';}letfood=newFood('包子',1);console.log(food.name);//包子例子4,调用匿名函数constanimals=[{name:'King'},{name:'Fail'}];for(leti=0;i