前端工作和面试经常会遇到修改this方向的问题,绕不开call,apply,bind的讨论用法一、调用语法:function.call(thisArg,arg1,arg2,...)其中:thisArg是可选值;当指定为null或undefined时,将自动替换为全局对象(严格模式下为undefined);指定为数字、字符串或布尔类型,将被转换成它们的包装对象。就是函数函数在运行时指向的this值。arg1,arg2,...指定的参数可以有多个返回值:用指定的this值和parameters调用函数的结果。使用场景://判断数据类型consta=1constb='1'constc=trueconstd=()=>{}toString.call(a)//输出'[objectNumber]'toString.call(b)//输出'[objectString]'toString.call(c)//输出'[objectBoolean]'toString.call(d)//输出'[objectFunction]'//将伪数组转换为数组functiontransformArgement(){constarr=Array.prototype.slice.call(arguments)returnarr}console.log(transformArgement(1,2,3,4,5))//输出[1,2,3,4,5]//通过调用父构造函数的call方法实现继承Calc(args){constarr=Array.prototype.slice.call(args)//最大值this.max=Math.max.apply(null,arr)//最小值this.min=Math.min.apply(null,arr)//求和this.sum=arr.reduce((pre,cur)=>pre+cur)}functionAges(){Calc.call(this,arguments)this.property='ages'}constteam01=newAges(10,20,12,80,4,100,19)console.log(team01.min)//输出4console.log(team01.max)//输出100console.log(team01.sum)//输出2452argsArray指定的参数可以是一个数组或类数组对象,其中数组元素将作为单独的参数传递给函数返回值:使用指定的this值和参数调用函数的结果使用场景://添加数组元素到数组constarr1=[1,2,3]constarr2=['1','2','3']Array.prototype.push.apply(arr1,arr2)console.log(arr1)//输出[1,2,3,'1','2','3']//数组转换constslice=Array.prototype.slice;functionargs(){returnslice.apply(arguments)}args(1,2,3,4)//return[1,2,3,4]//内置函数的扩展constarrNum=[1,4,6,3,2]console.log(Math.min.apply(null,arrNum))console.log(Math.max.apply(null,arrNum))3。绑定语法:function.bind(thisArg,arg1,arg2,...)其中:thisArg是调用绑定函数时作为this参数传递给目标函数的值。如果绑定函数是使用new运算符构造的,则忽略此值。当使用bind在setTimeout中创建函数(作为回调提供)时,作为thisArg传递的任何原始值都将转换为对象。如果bind函数的参数列表为空,或者thisArg为null或undefined,则执行范围内的this将被视为新函数的thisArg。arg1,arg2,...指定的参数可以有多个返回值:返回一个带有指定this值和初始参数的原始函数的副本。使用场景://创建一个绑定函数//新手常犯的错误是从对象中取出一个方法然后调用它,期望方法中的this是原始对象this.a=100constobj={a:1,fn:function(){returnthis.a}}obj.fn()//Output1constf=obj.fn.bind(obj)f()//Output1//React组件中的函数绑定定义组件实例classFooextendsComponent{constructor(props){super(props);this.handleClick=this.handleClick.bind(this);}handleClick(){console.log('点击发生');}render(){return
