call,apply,bind

张开发
2026/4/16 12:34:40 15 分钟阅读

分享文章

call,apply,bind
Function内置的实例方法call,apply一般是用来改变执行上下文的比如我们写了一个方法A在A里面需要写相同的逻辑这个时候就可以用call,apply来复用这些逻辑。如下文我们需要Food里面name的内容明明直接在Food里面执行this.namename就好了但是我们用call去继承了Product的函数内容这样就不需要重复写一遍了。工作中写一些基础类公共的函数的时候就可以考虑使用他们。functionProduct(name, price){this.namenamethis.pricepricethis.discountfunction(){returnthis.price*0.9}}functionFood(name, price){Product.call(this,name,price)this.categoryfood}constcheesenewFood(cheese,5)console.log(cheese.discount())// ✅ 输出: 4.5console.log(cheese.name)call和apply的共同特点就是能够改变函数的执行上下文将一个对象的方法交给另一个对象来执行而且是立即被调用的。区别在于call:调用call的对象必须是一个函数Function.call(obj,...args)第一个是一个对象,后续函数的调用者都会指向这个对象从第二个参数开始所有的参数都会映射到Function接收到的对象上面如果传入的是数组的话那么函数的第一个参数接收的是这个数组后续都为undefiedfunctionProduct(name, price){this.namenamethis.pricepricethis.discountfunction(){returnthis.price*0.9}}functionFood(name, price){Product.call(this,name,price)// 借用 Product 的初始化逻辑this.categoryfood}constcheesenewFood(cheese,5)console.log(cheese.discount())// ✅ 输出: 4.5console.log(cheese.name)// ✅ 输出: cheeseapply:和call的基本一致区别在于第二个参数apply传入的是一个数组或类数组中functiontest(a,b,c){console.log(a,b,c)}Function.prototype.myApplyfunction(context,arr){if(contextnull||contextundefined){contexttypeofwindow!undefined?window:global}constkeySymbol()context[key]thisconstresultcontext[key](...arr)deletecontext[key]returnresult}test.apply(null,[1,2,3])// 1,2,3test.myApply(null,[1,2,3])bind:调用apply的对象必须是一个函数Function.bind(obj,...args)call和apply是立即被执行的而apply不一样他是返回了一个函数在被调用的时候才会进行执行。functionmyBind(context,...boundArgs){// 保存原函数constoriginalFunctionthis// 返回新函数returnfunction(...callArgs){// 合并参数bind 时传入的参数 调用时传入的参数constallArgs[...boundArgs,...callArgs]// 使用 apply 执行原函数returnoriginalFunction.apply(context,allArgs)}}

更多文章